1use crate::development::{Actor, ToolAuthorization, ToolCall};
4use crate::{
5 DevelopmentToolContext, DevelopmentWorkspace, ResidentAgentBroker, WorkspaceTrustStore,
6};
7use glass_browser::cli::args::DaemonCommand;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use std::cell::RefCell;
11use std::collections::{BTreeMap, VecDeque};
12use std::path::{Path, PathBuf};
13use std::rc::Rc;
14use std::sync::{Arc, Mutex};
15use std::time::{Duration, SystemTime, UNIX_EPOCH};
16use tokio::io::{AsyncBufReadExt, AsyncRead, AsyncWrite, AsyncWriteExt, BufReader};
17
18const PROTOCOL_VERSION: u32 = 1;
19const MAX_REQUEST_BYTES: usize = 1024 * 1024;
20const MAX_RESPONSE_BYTES: usize = 1024 * 1024;
21const MAX_WORKSPACES: usize = 8;
22const MAX_CLIENTS: usize = 16;
23const WORKSPACE_COMMAND_CAPACITY: usize = 64;
24const WORKSPACE_EVENT_CAPACITY: usize = 512;
25const MAX_EVENT_BATCH: usize = 256;
26const DAEMON_REQUEST_TIMEOUT: Duration = Duration::from_secs(10);
27const OPERATION_CAPACITY: usize = 128;
28const OPERATION_EVENT_CAPACITY: usize = 512;
29
30type WorkspaceRegistry = Rc<RefCell<BTreeMap<String, WorkspaceActorHandle>>>;
31type QueuedOperation = (String, ToolCall, Box<DevelopmentToolContext>);
32type OperationExecution = (
33 DevelopmentWorkspace,
34 String,
35 String,
36 u64,
37 Result<Value, String>,
38);
39type OperationCompletion = Result<OperationExecution, tokio::task::JoinError>;
40
41#[derive(Clone)]
42struct WorkspaceActorHandle {
43 sender: tokio::sync::mpsc::Sender<WorkspaceCommand>,
44 summary: Value,
45 operations: Arc<Mutex<OperationRegistry>>,
46}
47
48enum WorkspaceCommand {
49 Inspect {
50 response: tokio::sync::oneshot::Sender<Result<Value, String>>,
51 },
52 Tool {
53 call: ToolCall,
54 context: Box<DevelopmentToolContext>,
55 response: tokio::sync::oneshot::Sender<Result<Value, String>>,
56 },
57 SubmitOperation {
58 operation_id: String,
59 call: ToolCall,
60 context: Box<DevelopmentToolContext>,
61 },
62 Events {
63 since: u64,
64 limit: usize,
65 response: tokio::sync::oneshot::Sender<Value>,
66 },
67 Shutdown {
68 response: tokio::sync::oneshot::Sender<()>,
69 },
70}
71
72#[derive(Debug, Clone, Serialize, Deserialize)]
73#[serde(rename_all = "camelCase")]
74pub struct DevelopmentDaemonStatus {
75 pub protocol_version: u32,
76 pub state: String,
77 pub pid: u32,
78 pub socket: PathBuf,
79 pub status_path: PathBuf,
80 pub token_path: PathBuf,
81 pub started_at_ms: u128,
82 pub workspace_count: usize,
83 pub client_count: usize,
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
87#[serde(rename_all = "camelCase")]
88pub struct DevelopmentDaemonRequest {
89 pub id: String,
90 pub token: String,
91 pub operation: String,
92 pub workspace_id: Option<String>,
93 pub root: Option<PathBuf>,
94 pub call: Option<ToolCall>,
95 pub expected_generation: Option<u64>,
96 pub expected_project_revision: Option<u64>,
97 #[serde(default)]
98 pub allow_mutation: bool,
99 #[serde(default)]
100 pub confirmed: bool,
101 pub actor: Option<String>,
102 #[serde(default)]
103 pub since: Option<u64>,
104 #[serde(default)]
105 pub limit: Option<usize>,
106 pub operation_id: Option<String>,
107}
108
109#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub enum DevelopmentOperationState {
112 Queued,
113 Running,
114 Succeeded,
115 Failed,
116 Cancelled,
117 Indeterminate,
118}
119
120impl DevelopmentOperationState {
121 fn terminal(self) -> bool {
122 matches!(
123 self,
124 Self::Succeeded | Self::Failed | Self::Cancelled | Self::Indeterminate
125 )
126 }
127}
128
129#[derive(Debug, Clone, Serialize, Deserialize)]
130#[serde(rename_all = "camelCase")]
131pub struct DevelopmentOperation {
132 pub id: String,
133 pub workspace_id: String,
134 pub actor: String,
135 pub operation_type: String,
136 pub state: DevelopmentOperationState,
137 pub submitted_at_ms: u128,
138 pub started_at_ms: Option<u128>,
139 pub completed_at_ms: Option<u128>,
140 pub revision_before: u64,
141 pub revision_after: Option<u64>,
142 pub result_ref: Option<String>,
143 pub result: Option<Value>,
144 pub failure_reason: Option<String>,
145 pub retry_safe: bool,
146 pub indeterminate: bool,
147 pub cancellation_requested: bool,
148}
149
150#[derive(Debug, Clone, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152pub struct DevelopmentOperationEvent {
153 pub sequence: u64,
154 pub operation_id: String,
155 pub timestamp_ms: u128,
156 pub state: DevelopmentOperationState,
157 pub message: String,
158}
159
160struct OperationRegistry {
161 workspace_id: String,
162 records: BTreeMap<String, DevelopmentOperation>,
163 order: VecDeque<String>,
164 idempotency: BTreeMap<String, String>,
165 events: VecDeque<DevelopmentOperationEvent>,
166 next_operation: u64,
167 next_event: u64,
168}
169
170impl OperationRegistry {
171 fn new(workspace_id: String) -> Self {
172 Self {
173 workspace_id,
174 records: BTreeMap::new(),
175 order: VecDeque::new(),
176 idempotency: BTreeMap::new(),
177 events: VecDeque::new(),
178 next_operation: 1,
179 next_event: 1,
180 }
181 }
182
183 fn submit(
184 &mut self,
185 request_id: &str,
186 actor: String,
187 operation_type: String,
188 revision_before: u64,
189 retry_safe: bool,
190 ) -> Result<(DevelopmentOperation, bool), String> {
191 if let Some(operation_id) = self.idempotency.get(request_id) {
192 return self
193 .records
194 .get(operation_id)
195 .cloned()
196 .map(|record| (record, false))
197 .ok_or_else(|| "operation idempotency record is inconsistent".into());
198 }
199 self.prune_terminal();
200 if self.records.len() >= OPERATION_CAPACITY {
201 return Err("workspace operation retention limit reached".into());
202 }
203 let id = format!("{}-op-{:06}", self.workspace_id, self.next_operation);
204 self.next_operation = self.next_operation.saturating_add(1);
205 let record = DevelopmentOperation {
206 id: id.clone(),
207 workspace_id: self.workspace_id.clone(),
208 actor,
209 operation_type,
210 state: DevelopmentOperationState::Queued,
211 submitted_at_ms: now_ms(),
212 started_at_ms: None,
213 completed_at_ms: None,
214 revision_before,
215 revision_after: None,
216 result_ref: None,
217 result: None,
218 failure_reason: None,
219 retry_safe,
220 indeterminate: false,
221 cancellation_requested: false,
222 };
223 self.records.insert(id.clone(), record.clone());
224 self.order.push_back(id.clone());
225 self.idempotency.insert(request_id.into(), id.clone());
226 self.event(&id, DevelopmentOperationState::Queued, "operation accepted");
227 Ok((record, true))
228 }
229
230 fn prune_terminal(&mut self) {
231 while self.records.len() >= OPERATION_CAPACITY {
232 let Some(id) = self.order.iter().find_map(|id| {
233 self.records
234 .get(id)
235 .is_some_and(|record| record.state.terminal())
236 .then(|| id.clone())
237 }) else {
238 break;
239 };
240 self.order.retain(|operation_id| operation_id != &id);
241 self.records.remove(&id);
242 self.idempotency
243 .retain(|_, operation_id| operation_id != &id);
244 }
245 }
246
247 fn event(&mut self, id: &str, state: DevelopmentOperationState, message: &str) {
248 if self.events.len() == OPERATION_EVENT_CAPACITY {
249 self.events.pop_front();
250 }
251 self.events.push_back(DevelopmentOperationEvent {
252 sequence: self.next_event,
253 operation_id: id.into(),
254 timestamp_ms: now_ms(),
255 state,
256 message: message.into(),
257 });
258 self.next_event = self.next_event.saturating_add(1);
259 }
260
261 fn start(&mut self, id: &str) -> bool {
262 let Some(record) = self.records.get_mut(id) else {
263 return false;
264 };
265 if record.cancellation_requested {
266 record.state = DevelopmentOperationState::Cancelled;
267 record.completed_at_ms = Some(now_ms());
268 self.event(
269 id,
270 DevelopmentOperationState::Cancelled,
271 "cancelled before start",
272 );
273 return false;
274 }
275 record.state = DevelopmentOperationState::Running;
276 record.started_at_ms = Some(now_ms());
277 self.event(id, DevelopmentOperationState::Running, "operation started");
278 true
279 }
280
281 fn finish(&mut self, id: &str, revision_after: u64, result: Result<Value, String>) {
282 let Some(record) = self.records.get_mut(id) else {
283 return;
284 };
285 record.revision_after = Some(revision_after);
286 record.completed_at_ms = Some(now_ms());
287 let (state, message) = if record.cancellation_requested {
288 record.state = DevelopmentOperationState::Cancelled;
289 record.result = None;
290 record.failure_reason =
291 Some("operation completed after cancellation was requested".into());
292 (DevelopmentOperationState::Cancelled, "operation cancelled")
293 } else {
294 match result {
295 Ok(value) => {
296 record.state = DevelopmentOperationState::Succeeded;
297 record.result_ref =
298 Some(format!("operation://{}/{}/result", self.workspace_id, id));
299 record.result = Some(value);
300 (DevelopmentOperationState::Succeeded, "operation succeeded")
301 }
302 Err(error) => {
303 record.state = DevelopmentOperationState::Failed;
304 record.failure_reason = Some(error);
305 (DevelopmentOperationState::Failed, "operation failed")
306 }
307 }
308 };
309 self.event(id, state, message);
310 }
311
312 fn indeterminate(&mut self, id: &str, error: String) {
313 if let Some(record) = self.records.get_mut(id) {
314 record.state = DevelopmentOperationState::Indeterminate;
315 record.indeterminate = true;
316 record.failure_reason = Some(error);
317 record.completed_at_ms = Some(now_ms());
318 }
319 self.event(
320 id,
321 DevelopmentOperationState::Indeterminate,
322 "operation outcome is indeterminate",
323 );
324 }
325
326 fn cancel(&mut self, id: &str) -> Result<DevelopmentOperation, String> {
327 let (state, record) = {
328 let record = self
329 .records
330 .get_mut(id)
331 .ok_or_else(|| "unknown workspace operation".to_string())?;
332 if !record.state.terminal() {
333 record.cancellation_requested = true;
334 if record.state == DevelopmentOperationState::Queued {
335 record.state = DevelopmentOperationState::Cancelled;
336 record.completed_at_ms = Some(now_ms());
337 }
338 }
339 (record.state, record.clone())
340 };
341 self.event(id, state, "cancellation requested");
342 Ok(record)
343 }
344}
345
346#[derive(Debug, Clone, Serialize, Deserialize)]
347#[serde(rename_all = "camelCase")]
348pub struct DevelopmentDaemonEvent {
349 pub sequence: u64,
350 pub timestamp_ms: u128,
351 pub kind: String,
352 pub workspace_id: String,
353 pub tool_call_id: Option<String>,
354 pub success: bool,
355}
356
357#[derive(Debug, Clone, Serialize, Deserialize)]
358#[serde(rename_all = "camelCase")]
359pub struct DevelopmentDaemonResponse {
360 pub id: String,
361 pub ok: bool,
362 pub result: Value,
363 pub error: Option<String>,
364}
365
366pub async fn dispatch(action: &DaemonCommand) -> Result<(), Box<dyn std::error::Error>> {
367 match action {
368 DaemonCommand::Start { socket, status } => {
369 println!(
370 "{}",
371 serde_json::to_string_pretty(&start(socket.as_deref(), status.as_deref()).await?)?
372 );
373 }
374 DaemonCommand::Status { socket, status } | DaemonCommand::Doctor { socket, status } => {
375 println!(
376 "{}",
377 serde_json::to_string_pretty(&read_status_checked(
378 socket.as_deref(),
379 status.as_deref()
380 )?)?
381 );
382 }
383 DaemonCommand::Stop { socket, status } => {
384 stop(socket.as_deref(), status.as_deref())?;
385 println!("{{\"status\":\"stopped\"}}");
386 }
387 DaemonCommand::Logs { status } => {
388 let (_, default_status) = default_paths();
389 let status = status.as_deref().unwrap_or(&default_status);
390 print!("{}", bounded_log(status)?);
391 }
392 DaemonCommand::AcknowledgeRecovery { .. } => {
393 println!("{{\"status\":\"no-recovery-required\"}}");
394 }
395 DaemonCommand::Serve { socket, status } => serve(socket, status).await?,
396 }
397 Ok(())
398}
399
400pub fn default_paths() -> (PathBuf, PathBuf) {
401 #[cfg(windows)]
402 let base =
403 dirs::data_local_dir().unwrap_or_else(|| std::env::temp_dir().join("glass-current-user"));
404 #[cfg(not(windows))]
405 let base = std::env::var_os("XDG_RUNTIME_DIR")
406 .map(PathBuf::from)
407 .or_else(|| std::env::var_os("XDG_DATA_HOME").map(PathBuf::from))
408 .unwrap_or_else(|| std::env::temp_dir().join(format!("glass-{}", effective_uid())));
409 let root = base.join("glass-dev");
410 #[cfg(windows)]
411 {
412 use std::hash::{Hash, Hasher};
413 let mut hasher = std::hash::DefaultHasher::new();
414 root.hash(&mut hasher);
415 let endpoint = PathBuf::from(format!(r"\\.\pipe\glass-dev-{:016x}", hasher.finish()));
416 (endpoint, root.join("glassd.json"))
417 }
418 #[cfg(not(windows))]
419 {
420 (root.join("glassd.sock"), root.join("glassd.json"))
421 }
422}
423
424pub async fn start(
425 socket: Option<&Path>,
426 status_path: Option<&Path>,
427) -> Result<DevelopmentDaemonStatus, Box<dyn std::error::Error>> {
428 #[cfg(not(any(unix, windows)))]
429 {
430 let _ = (socket, status_path);
431 return Err("the durable development daemon currently requires Unix local sockets".into());
432 }
433 #[cfg(unix)]
434 {
435 let (default_socket, default_status) = default_paths();
436 let socket = socket.unwrap_or(&default_socket);
437 let status_path = status_path.unwrap_or(&default_status);
438 if let Ok(existing) = read_status(status_path)
439 && process_alive(existing.pid)
440 {
441 return Err(
442 format!("development daemon is already running as {}", existing.pid).into(),
443 );
444 }
445 remove_socket_if_safe(socket)?;
446 if status_path.exists() {
447 std::fs::remove_file(status_path)?;
448 }
449 std::fs::create_dir_all(socket.parent().unwrap_or_else(|| Path::new(".")))?;
450 std::fs::create_dir_all(status_path.parent().unwrap_or_else(|| Path::new(".")))?;
451 let log = log_path(status_path);
452 let stdout = std::fs::OpenOptions::new()
453 .create(true)
454 .append(true)
455 .open(&log)?;
456 let stderr = stdout.try_clone()?;
457 std::process::Command::new(std::env::current_exe()?)
458 .args(["daemon", "serve"])
459 .arg("--socket")
460 .arg(socket)
461 .arg("--status")
462 .arg(status_path)
463 .stdin(std::process::Stdio::null())
464 .stdout(std::process::Stdio::from(stdout))
465 .stderr(std::process::Stdio::from(stderr))
466 .spawn()?;
467 let deadline = std::time::Instant::now() + Duration::from_secs(3);
468 loop {
469 if let Ok(status) = read_status(status_path)
470 && process_alive(status.pid)
471 && status.socket == socket
472 {
473 return Ok(status);
474 }
475 if std::time::Instant::now() >= deadline {
476 return Err("development daemon did not become ready within three seconds".into());
477 }
478 tokio::time::sleep(Duration::from_millis(25)).await;
479 }
480 }
481 #[cfg(windows)]
482 {
483 let (default_socket, default_status) = default_paths();
484 let socket = socket.unwrap_or(&default_socket);
485 let status_path = status_path.unwrap_or(&default_status);
486 validate_windows_pipe_name(socket)?;
487 if let Ok(existing) = read_status(status_path)
488 && process_alive(existing.pid)
489 {
490 return Err(
491 format!("development daemon is already running as {}", existing.pid).into(),
492 );
493 }
494 if status_path.exists() {
495 std::fs::remove_file(status_path)?;
496 }
497 std::fs::create_dir_all(status_path.parent().unwrap_or_else(|| Path::new(".")))?;
498 let log = log_path(status_path);
499 let stdout = std::fs::OpenOptions::new()
500 .create(true)
501 .append(true)
502 .open(&log)?;
503 let stderr = stdout.try_clone()?;
504 std::process::Command::new(std::env::current_exe()?)
505 .args(["daemon", "serve"])
506 .arg("--socket")
507 .arg(socket)
508 .arg("--status")
509 .arg(status_path)
510 .stdin(std::process::Stdio::null())
511 .stdout(std::process::Stdio::from(stdout))
512 .stderr(std::process::Stdio::from(stderr))
513 .spawn()?;
514 let deadline = std::time::Instant::now() + Duration::from_secs(3);
515 loop {
516 if let Ok(status) = read_status(status_path)
517 && process_alive(status.pid)
518 && status.socket == socket
519 {
520 return Ok(status);
521 }
522 if std::time::Instant::now() >= deadline {
523 return Err("development daemon did not become ready within three seconds".into());
524 }
525 tokio::time::sleep(Duration::from_millis(25)).await;
526 }
527 }
528}
529
530pub fn read_status_checked(
531 socket: Option<&Path>,
532 status_path: Option<&Path>,
533) -> Result<DevelopmentDaemonStatus, Box<dyn std::error::Error>> {
534 let (default_socket, default_status) = default_paths();
535 let expected_socket = socket.unwrap_or(&default_socket);
536 let status_path = status_path.unwrap_or(&default_status);
537 let mut status = read_status(status_path)?;
538 validate_status(&status, status_path)?;
539 if status.socket != expected_socket {
540 return Err("daemon status socket does not match the requested socket".into());
541 }
542 if !process_alive(status.pid) {
543 status.state = "stopped".into();
544 }
545 Ok(status)
546}
547
548pub fn stop(
549 socket: Option<&Path>,
550 status_path: Option<&Path>,
551) -> Result<(), Box<dyn std::error::Error>> {
552 #[cfg(not(any(unix, windows)))]
553 {
554 let _ = (socket, status_path);
555 return Err("the durable development daemon currently requires Unix".into());
556 }
557 #[cfg(unix)]
558 {
559 let status = read_status_checked(socket, status_path)?;
560 if status.pid == std::process::id() {
561 return Err("refusing to stop the calling process".into());
562 }
563 let result = unsafe { libc::kill(status.pid as i32, libc::SIGTERM) };
564 if result != 0 {
565 return Err(std::io::Error::last_os_error().into());
566 }
567 Ok(())
568 }
569 #[cfg(windows)]
570 {
571 use windows_sys::Win32::System::Threading::{
572 OpenProcess, PROCESS_TERMINATE, TerminateProcess,
573 };
574 let status = read_status_checked(socket, status_path)?;
575 if status.pid == std::process::id() {
576 return Err("refusing to stop the calling process".into());
577 }
578 let process = unsafe { OpenProcess(PROCESS_TERMINATE, 0, status.pid) };
579 if process.is_null() {
580 return Err(std::io::Error::last_os_error().into());
581 }
582 let terminated = unsafe { TerminateProcess(process, 0) };
583 unsafe { windows_sys::Win32::Foundation::CloseHandle(process) };
584 if terminated == 0 {
585 return Err(std::io::Error::last_os_error().into());
586 }
587 Ok(())
588 }
589}
590
591pub async fn serve(socket: &Path, status_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
592 serve_with_store(
593 socket,
594 status_path,
595 WorkspaceTrustStore::platform_default()?,
596 )
597 .await
598}
599
600async fn serve_with_store(
601 socket: &Path,
602 status_path: &Path,
603 trust_store: WorkspaceTrustStore,
604) -> Result<(), Box<dyn std::error::Error>> {
605 #[cfg(not(any(unix, windows)))]
606 {
607 let _ = (socket, status_path);
608 return Err("the durable development daemon currently requires Unix".into());
609 }
610 #[cfg(unix)]
611 {
612 use std::os::unix::fs::PermissionsExt;
613 use tokio::net::UnixListener;
614 use tokio::signal::unix::{SignalKind, signal};
615
616 remove_socket_if_safe(socket)?;
617 std::fs::create_dir_all(socket.parent().unwrap_or_else(|| Path::new(".")))?;
618 std::fs::create_dir_all(status_path.parent().unwrap_or_else(|| Path::new(".")))?;
619 let listener = UnixListener::bind(socket)?;
620 std::fs::set_permissions(socket, std::fs::Permissions::from_mode(0o600))?;
621 let token_path = token_path(status_path);
622 let token = create_token()?;
623 write_private(&token_path, token.as_bytes())?;
624 let status = DevelopmentDaemonStatus {
625 protocol_version: PROTOCOL_VERSION,
626 state: "running".into(),
627 pid: std::process::id(),
628 socket: socket.to_path_buf(),
629 status_path: status_path.to_path_buf(),
630 token_path: token_path.clone(),
631 started_at_ms: now_ms(),
632 workspace_count: 0,
633 client_count: 0,
634 };
635 write_status(status_path, &status)?;
636 let workspaces: WorkspaceRegistry = Rc::new(RefCell::new(BTreeMap::new()));
637 let clients = std::rc::Rc::new(std::cell::Cell::new(0_usize));
638 let local = tokio::task::LocalSet::new();
639 let mut terminate = signal(SignalKind::terminate())?;
640 local
641 .run_until(async {
642 loop {
643 let (stream, _) = tokio::select! {
644 accepted = listener.accept() => accepted?,
645 _ = terminate.recv() => break,
646 };
647 authorize_local_peer(&stream)?;
648 if clients.get() >= MAX_CLIENTS {
649 continue;
650 }
651 clients.set(clients.get() + 1);
652 update_counts(status_path, workspaces.borrow().len(), clients.get())?;
653 let workspaces = Rc::clone(&workspaces);
654 let clients = Rc::clone(&clients);
655 let token = token.clone();
656 let status_path = status_path.to_path_buf();
657 let socket = socket.to_path_buf();
658 let trust_store = trust_store.clone();
659 tokio::task::spawn_local(async move {
660 if let Err(error) =
661 handle_client(stream, &token, &socket, &workspaces, &trust_store).await
662 {
663 tracing::warn!(%error, "development daemon client failed");
664 }
665 clients.set(clients.get().saturating_sub(1));
666 let workspace_count = workspaces.borrow().len();
667 let _ = update_counts(&status_path, workspace_count, clients.get());
668 });
669 }
670 Ok::<(), Box<dyn std::error::Error>>(())
671 })
672 .await?;
673 let _ = std::fs::remove_file(status_path);
674 let _ = std::fs::remove_file(token_path);
675 remove_socket_if_safe(socket)?;
676 Ok(())
677 }
678 #[cfg(windows)]
679 {
680 use tokio::net::windows::named_pipe::ServerOptions;
681
682 validate_windows_pipe_name(socket)?;
683 std::fs::create_dir_all(status_path.parent().unwrap_or_else(|| Path::new(".")))?;
684 let token_path = token_path(status_path);
685 let token = create_token()?;
686 write_private(&token_path, token.as_bytes())?;
687 let status = DevelopmentDaemonStatus {
688 protocol_version: PROTOCOL_VERSION,
689 state: "running".into(),
690 pid: std::process::id(),
691 socket: socket.to_path_buf(),
692 status_path: status_path.to_path_buf(),
693 token_path: token_path.clone(),
694 started_at_ms: now_ms(),
695 workspace_count: 0,
696 client_count: 0,
697 };
698 write_status(status_path, &status)?;
699 let workspaces: WorkspaceRegistry = Rc::new(RefCell::new(BTreeMap::new()));
700 let clients = Rc::new(std::cell::Cell::new(0_usize));
701 let local = tokio::task::LocalSet::new();
702 let pipe_name = socket.to_string_lossy().to_string();
703 local
704 .run_until(async {
705 let mut first = true;
706 loop {
707 let server = ServerOptions::new()
708 .first_pipe_instance(first)
709 .reject_remote_clients(true)
710 .create(&pipe_name)?;
711 first = false;
712 tokio::select! {
713 connected = server.connect() => connected?,
714 _ = tokio::signal::ctrl_c() => break,
715 }
716 if clients.get() >= MAX_CLIENTS {
717 continue;
718 }
719 clients.set(clients.get() + 1);
720 update_counts(status_path, workspaces.borrow().len(), clients.get())?;
721 let workspaces = Rc::clone(&workspaces);
722 let clients = Rc::clone(&clients);
723 let token = token.clone();
724 let status_path = status_path.to_path_buf();
725 let socket = socket.to_path_buf();
726 let trust_store = trust_store.clone();
727 tokio::task::spawn_local(async move {
728 if let Err(error) =
729 handle_stream(server, &token, &socket, &workspaces, &trust_store).await
730 {
731 tracing::warn!(%error, "development daemon named-pipe client failed");
732 }
733 clients.set(clients.get().saturating_sub(1));
734 let _ =
735 update_counts(&status_path, workspaces.borrow().len(), clients.get());
736 });
737 }
738 Ok::<(), Box<dyn std::error::Error>>(())
739 })
740 .await?;
741 let _ = std::fs::remove_file(status_path);
742 let _ = std::fs::remove_file(token_path);
743 Ok(())
744 }
745}
746
747#[cfg(unix)]
748async fn handle_client(
749 stream: tokio::net::UnixStream,
750 token: &str,
751 socket: &Path,
752 workspaces: &WorkspaceRegistry,
753 trust_store: &WorkspaceTrustStore,
754) -> Result<(), Box<dyn std::error::Error>> {
755 handle_stream(stream, token, socket, workspaces, trust_store).await
756}
757
758async fn handle_stream<S>(
759 stream: S,
760 token: &str,
761 socket: &Path,
762 workspaces: &WorkspaceRegistry,
763 trust_store: &WorkspaceTrustStore,
764) -> Result<(), Box<dyn std::error::Error>>
765where
766 S: AsyncRead + AsyncWrite + Unpin,
767{
768 let (read, mut write) = tokio::io::split(stream);
769 let mut lines = BufReader::new(read).lines();
770 while let Some(line) = lines.next_line().await? {
771 let response = if line.len() > MAX_REQUEST_BYTES {
772 DevelopmentDaemonResponse {
773 id: "oversized".into(),
774 ok: false,
775 result: Value::Null,
776 error: Some("daemon request exceeds the size limit".into()),
777 }
778 } else {
779 match serde_json::from_str::<DevelopmentDaemonRequest>(&line) {
780 Ok(request) => {
781 execute_request(request, token, socket, workspaces, trust_store).await
782 }
783 Err(error) => DevelopmentDaemonResponse {
784 id: "invalid".into(),
785 ok: false,
786 result: Value::Null,
787 error: Some(format!("invalid daemon request: {error}")),
788 },
789 }
790 };
791 let encoded = serde_json::to_vec(&response)?;
792 if encoded.len() > MAX_RESPONSE_BYTES {
793 return Err("daemon response exceeds the size limit".into());
794 }
795 write.write_all(&encoded).await?;
796 write.write_all(b"\n").await?;
797 write.flush().await?;
798 }
799 Ok(())
800}
801
802async fn execute_request(
803 request: DevelopmentDaemonRequest,
804 token: &str,
805 socket: &Path,
806 workspaces: &WorkspaceRegistry,
807 trust_store: &WorkspaceTrustStore,
808) -> DevelopmentDaemonResponse {
809 let id = request.id.clone();
810 let result = async {
811 validate_request(&request, token)?;
812 match request.operation.as_str() {
813 "ping" => Ok(serde_json::json!({"protocolVersion":PROTOCOL_VERSION})),
814 "workspace.list" => Ok(Value::Array(
815 workspaces
816 .borrow()
817 .values()
818 .map(|handle| handle.summary.clone())
819 .collect(),
820 )),
821 "workspace.open" => {
822 let workspace_id = required_workspace_id(&request)?;
823 let root = request
824 .root
825 .as_deref()
826 .ok_or("workspace.open requires root")?;
827 if workspaces.borrow().contains_key(workspace_id) {
828 return Err("workspace identity is already open".into());
829 }
830 if workspaces.borrow().len() >= MAX_WORKSPACES {
831 return Err("daemon workspace quota reached".into());
832 }
833 let mut workspace =
834 DevelopmentWorkspace::open_with_store(root, trust_store.clone())
835 .map_err(|error| error.to_string())?;
836 workspace
837 .agents()
838 .set_resident_broker(ResidentAgentBroker {
839 socket: socket.to_path_buf(),
840 token: token.to_string(),
841 workspace_id: workspace_id.to_string(),
842 })
843 .map_err(|error| error.to_string())?;
844 let result = workspace_summary(workspace_id, &workspace);
845 let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
846 let operations = Arc::new(Mutex::new(OperationRegistry::new(workspace_id.into())));
847 tokio::task::spawn_local(run_workspace_actor(
848 workspace_id.into(),
849 workspace,
850 receiver,
851 Arc::clone(&operations),
852 ));
853 let mut state = workspaces.borrow_mut();
854 if state.contains_key(workspace_id) || state.len() >= MAX_WORKSPACES {
855 return Err("daemon workspace registry changed while opening".into());
856 }
857 state.insert(
858 workspace_id.into(),
859 WorkspaceActorHandle {
860 sender,
861 summary: result.clone(),
862 operations,
863 },
864 );
865 Ok(result)
866 }
867 "workspace.inspect" => {
868 let workspace_id = required_workspace_id(&request)?;
869 workspace_inspect(workspace_handle(workspaces, workspace_id)?).await
870 }
871 "workspace.tool" => {
872 let workspace_id = required_workspace_id(&request)?;
873 let call = request
874 .call
875 .as_ref()
876 .ok_or("workspace.tool requires call")?;
877 if request.allow_mutation || long_operation_tool(&call.name) {
878 return Err(
879 "mutating or long-running tools require operation.submit so clients can reconnect and reconcile"
880 .into(),
881 );
882 }
883 let context = request_tool_context(&request, "workspace.tool")?;
884 workspace_tool(
885 workspace_handle(workspaces, workspace_id)?,
886 call.clone(),
887 context,
888 )
889 .await
890 }
891 "operation.submit" => {
892 let workspace_id = required_workspace_id(&request)?;
893 let call = request
894 .call
895 .as_ref()
896 .ok_or("operation.submit requires call")?;
897 let context = request_tool_context(&request, "operation.submit")?;
898 let handle = workspace_handle(workspaces, workspace_id)?;
899 let actor = request.actor.clone().unwrap_or_else(|| "local".into());
900 let (operation, created) = handle
901 .operations
902 .lock()
903 .map_err(|_| "workspace operation registry is poisoned")?
904 .submit(
905 &request.id,
906 actor,
907 call.name.clone(),
908 context.expected_project_revision,
909 !request.allow_mutation,
910 )?;
911 if created
912 && handle
913 .sender
914 .try_send(WorkspaceCommand::SubmitOperation {
915 operation_id: operation.id.clone(),
916 call: call.clone(),
917 context: Box::new(context),
918 })
919 .is_err()
920 {
921 if let Ok(mut registry) = handle.operations.lock() {
922 registry.indeterminate(
923 &operation.id,
924 "workspace actor command queue closed".into(),
925 );
926 }
927 return Err("workspace actor command queue closed".into());
928 }
929 Ok(serde_json::json!({"accepted":true,"created":created,"operation":operation}))
930 }
931 "operation.inspect" | "operation.reconcile" => {
932 let workspace_id = required_workspace_id(&request)?;
933 let operation_id = required_operation_id(&request)?;
934 let handle = workspace_handle(workspaces, workspace_id)?;
935 let operation = handle
936 .operations
937 .lock()
938 .map_err(|_| "workspace operation registry is poisoned")?
939 .records
940 .get(operation_id)
941 .cloned()
942 .ok_or("unknown workspace operation")?;
943 let reconciled = operation.state.terminal();
944 let retry_safe = matches!(
945 operation.state,
946 DevelopmentOperationState::Failed
947 | DevelopmentOperationState::Cancelled
948 | DevelopmentOperationState::Indeterminate
949 ) && operation.retry_safe;
950 Ok(serde_json::json!({
951 "operation":operation,
952 "reconciled":reconciled,
953 "retrySafe":retry_safe,
954 }))
955 }
956 "operation.list" => {
957 let workspace_id = required_workspace_id(&request)?;
958 let handle = workspace_handle(workspaces, workspace_id)?;
959 let registry = handle
960 .operations
961 .lock()
962 .map_err(|_| "workspace operation registry is poisoned")?;
963 let operations = registry
964 .order
965 .iter()
966 .filter_map(|id| registry.records.get(id).cloned())
967 .collect::<Vec<_>>();
968 Ok(serde_json::json!({"operations":operations,"capacity":OPERATION_CAPACITY}))
969 }
970 "operation.cancel" => {
971 let workspace_id = required_workspace_id(&request)?;
972 let operation_id = required_operation_id(&request)?;
973 let handle = workspace_handle(workspaces, workspace_id)?;
974 let operation = handle
975 .operations
976 .lock()
977 .map_err(|_| "workspace operation registry is poisoned")?
978 .cancel(operation_id)?;
979 Ok(serde_json::json!({"operation":operation}))
980 }
981 "operation.events" => {
982 let workspace_id = required_workspace_id(&request)?;
983 let operation_id = request.operation_id.as_deref();
984 if let Some(operation_id) = operation_id {
985 validate_identifier(operation_id, "operation")?;
986 }
987 let limit = request.limit.unwrap_or(128);
988 if limit == 0 || limit > MAX_EVENT_BATCH {
989 return Err(format!(
990 "operation event limit must be 1..={MAX_EVENT_BATCH}"
991 ));
992 }
993 let handle = workspace_handle(workspaces, workspace_id)?;
994 let registry = handle
995 .operations
996 .lock()
997 .map_err(|_| "workspace operation registry is poisoned")?;
998 let since = request.since.unwrap_or(0);
999 let events = registry
1000 .events
1001 .iter()
1002 .filter(|event| event.sequence > since)
1003 .filter(|event| operation_id.is_none_or(|id| event.operation_id == id))
1004 .take(limit)
1005 .cloned()
1006 .collect::<Vec<_>>();
1007 Ok(serde_json::json!({
1008 "events":events,
1009 "newestSequence":registry.events.back().map_or(0, |event| event.sequence),
1010 "capacity":OPERATION_EVENT_CAPACITY,
1011 }))
1012 }
1013 "workspace.events" => {
1014 let workspace_id = required_workspace_id(&request)?;
1015 workspace_events(
1016 workspace_handle(workspaces, workspace_id)?,
1017 request.since.unwrap_or(0),
1018 request.limit.unwrap_or(128),
1019 )
1020 .await
1021 }
1022 "workspace.close" => {
1023 let workspace_id = required_workspace_id(&request)?;
1024 let handle = workspaces.borrow_mut().remove(workspace_id);
1025 if let Some(handle) = handle {
1026 let (response, received) = tokio::sync::oneshot::channel();
1027 handle
1028 .sender
1029 .send(WorkspaceCommand::Shutdown { response })
1030 .await
1031 .map_err(|_| "workspace actor command queue closed")?;
1032 received.await.map_err(|_| "workspace actor did not stop")?;
1033 Ok(serde_json::json!({"closed":true}))
1034 } else {
1035 Ok(serde_json::json!({"closed":false}))
1036 }
1037 }
1038 _ => Err("unknown daemon operation".into()),
1039 }
1040 }
1041 .await;
1042 match result {
1043 Ok(result) => DevelopmentDaemonResponse {
1044 id,
1045 ok: true,
1046 result,
1047 error: None,
1048 },
1049 Err(error) => DevelopmentDaemonResponse {
1050 id,
1051 ok: false,
1052 result: Value::Null,
1053 error: Some(error),
1054 },
1055 }
1056}
1057
1058fn workspace_handle(
1059 workspaces: &WorkspaceRegistry,
1060 workspace_id: &str,
1061) -> Result<WorkspaceActorHandle, String> {
1062 workspaces
1063 .borrow()
1064 .get(workspace_id)
1065 .cloned()
1066 .ok_or_else(|| "unknown durable workspace".into())
1067}
1068
1069async fn workspace_inspect(handle: WorkspaceActorHandle) -> Result<Value, String> {
1070 let (response, received) = tokio::sync::oneshot::channel();
1071 handle
1072 .sender
1073 .send(WorkspaceCommand::Inspect { response })
1074 .await
1075 .map_err(|_| "workspace actor command queue closed")?;
1076 received
1077 .await
1078 .map_err(|_| "workspace actor dropped its inspect response")?
1079}
1080
1081async fn workspace_tool(
1082 handle: WorkspaceActorHandle,
1083 call: ToolCall,
1084 context: DevelopmentToolContext,
1085) -> Result<Value, String> {
1086 let (response, received) = tokio::sync::oneshot::channel();
1087 handle
1088 .sender
1089 .send(WorkspaceCommand::Tool {
1090 call,
1091 context: Box::new(context),
1092 response,
1093 })
1094 .await
1095 .map_err(|_| "workspace actor command queue closed")?;
1096 received
1097 .await
1098 .map_err(|_| "workspace actor dropped its tool response")?
1099}
1100
1101async fn workspace_events(
1102 handle: WorkspaceActorHandle,
1103 since: u64,
1104 limit: usize,
1105) -> Result<Value, String> {
1106 if limit == 0 || limit > MAX_EVENT_BATCH {
1107 return Err(format!(
1108 "workspace event limit must be 1..={MAX_EVENT_BATCH}"
1109 ));
1110 }
1111 let (response, received) = tokio::sync::oneshot::channel();
1112 handle
1113 .sender
1114 .send(WorkspaceCommand::Events {
1115 since,
1116 limit,
1117 response,
1118 })
1119 .await
1120 .map_err(|_| "workspace actor command queue closed")?;
1121 received
1122 .await
1123 .map_err(|_| "workspace actor dropped its event response".into())
1124}
1125
1126async fn run_workspace_actor(
1127 workspace_id: String,
1128 workspace: DevelopmentWorkspace,
1129 mut commands: tokio::sync::mpsc::Receiver<WorkspaceCommand>,
1130 operations: Arc<Mutex<OperationRegistry>>,
1131) {
1132 let mut workspace = Some(workspace);
1133 let mut queued_operations: VecDeque<QueuedOperation> = VecDeque::new();
1134 let (completion_tx, mut completions) = tokio::sync::mpsc::channel::<OperationCompletion>(1);
1135 let mut operation_running = false;
1136 let mut command_channel_open = true;
1137 let mut closing: Option<tokio::sync::oneshot::Sender<()>> = None;
1138 let mut events = VecDeque::with_capacity(WORKSPACE_EVENT_CAPACITY);
1139 let mut next_event = 1_u64;
1140 let mut dropped_events = 0_u64;
1141 push_workspace_event(
1142 &workspace_id,
1143 &mut events,
1144 &mut next_event,
1145 &mut dropped_events,
1146 "workspace.opened",
1147 None,
1148 true,
1149 );
1150 let mut tick = tokio::time::interval(Duration::from_millis(50));
1151 tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
1152 loop {
1153 if closing.is_none() && !operation_running && workspace.is_some() {
1154 while let Some((operation_id, call, context)) = queued_operations.pop_front() {
1155 let should_start = operations
1156 .lock()
1157 .map(|mut registry| registry.start(&operation_id))
1158 .unwrap_or(false);
1159 if !should_start {
1160 continue;
1161 }
1162 let mut owned_workspace = workspace
1163 .take()
1164 .expect("workspace operation start owns the workspace");
1165 let completion = completion_tx.clone();
1166 operation_running = true;
1167 tokio::task::spawn_local(async move {
1168 let joined = tokio::task::spawn_blocking(move || {
1169 let result = owned_workspace
1170 .execute_tool(&call, &context)
1171 .map_err(|error| error.to_string());
1172 let revision_after = owned_workspace.project().revision();
1173 (
1174 owned_workspace,
1175 operation_id,
1176 call.id,
1177 revision_after,
1178 result,
1179 )
1180 })
1181 .await;
1182 let _ = completion.send(joined).await;
1183 });
1184 break;
1185 }
1186 }
1187 if closing.is_some() && !operation_running {
1188 if let Some(response) = closing.take() {
1189 let _ = response.send(());
1190 }
1191 break;
1192 }
1193 tokio::select! {
1194 biased;
1195 completion = completions.recv(), if operation_running => {
1196 operation_running = false;
1197 match completion {
1198 Some(Ok((returned_workspace, operation_id, call_id, revision_after, result))) => {
1199 workspace = Some(returned_workspace);
1200 if let Ok(mut registry) = operations.lock() {
1201 registry.finish(&operation_id, revision_after, result.clone());
1202 }
1203 push_workspace_event(
1204 &workspace_id,
1205 &mut events,
1206 &mut next_event,
1207 &mut dropped_events,
1208 "operation.completed",
1209 Some(call_id),
1210 result.is_ok(),
1211 );
1212 }
1213 Some(Err(error)) => {
1214 let running_id = operations.lock().ok().and_then(|registry| {
1215 registry.records.values().find(|record| {
1216 record.state == DevelopmentOperationState::Running
1217 }).map(|record| record.id.clone())
1218 });
1219 if let Some(operation_id) = running_id
1220 && let Ok(mut registry) = operations.lock()
1221 {
1222 registry.indeterminate(
1223 &operation_id,
1224 format!("workspace operation worker failed: {error}"),
1225 );
1226 }
1227 tracing::error!(workspace_id, %error, "workspace operation worker failed");
1228 if let Some(response) = closing.take() {
1229 let _ = response.send(());
1230 }
1231 break;
1232 }
1233 None => break,
1234 }
1235 }
1236 command = commands.recv(), if command_channel_open => match command {
1237 Some(WorkspaceCommand::Inspect { response }) => {
1238 let result = workspace.as_mut().map_or_else(
1239 || Err("workspace is busy with a recoverable operation; inspect the operation ID".into()),
1240 |workspace| inspect_workspace(&workspace_id, workspace),
1241 );
1242 let _ = response.send(result);
1243 }
1244 Some(WorkspaceCommand::Tool { call, context, response }) => {
1245 let Some(mut owned_workspace) = workspace.take() else {
1246 let _ = response.send(Err(
1247 "workspace is busy; submit long work with operation.submit and inspect its ID".into(),
1248 ));
1249 continue;
1250 };
1251 let kind = daemon_event_kind(&call.name);
1252 let execution = tokio::task::spawn_blocking(move || {
1253 let result = owned_workspace
1254 .execute_tool(&call, &context)
1255 .map_err(|error| error.to_string());
1256 (owned_workspace, call.id, result)
1257 })
1258 .await;
1259 let (returned_workspace, call_id, result) = match execution {
1260 Ok(execution) => execution,
1261 Err(error) => {
1262 let _ = response.send(Err(format!(
1263 "workspace actor tool execution failed: {error}"
1264 )));
1265 break;
1266 }
1267 };
1268 workspace = Some(returned_workspace);
1269 push_workspace_event(
1270 &workspace_id,
1271 &mut events,
1272 &mut next_event,
1273 &mut dropped_events,
1274 kind,
1275 Some(call_id),
1276 result.is_ok(),
1277 );
1278 let _ = response.send(result);
1279 }
1280 Some(WorkspaceCommand::SubmitOperation { operation_id, call, context }) => {
1281 queued_operations.push_back((operation_id, call, context));
1282 }
1283 Some(WorkspaceCommand::Events { since, limit, response }) => {
1284 let _ = response.send(workspace_event_batch(
1285 &events,
1286 next_event,
1287 dropped_events,
1288 since,
1289 limit,
1290 ));
1291 }
1292 Some(WorkspaceCommand::Shutdown { response }) => {
1293 if let Ok(mut registry) = operations.lock() {
1294 let active = registry
1295 .records
1296 .values()
1297 .filter(|record| !record.state.terminal())
1298 .map(|record| record.id.clone())
1299 .collect::<Vec<_>>();
1300 for id in active {
1301 let _ = registry.cancel(&id);
1302 }
1303 }
1304 queued_operations.clear();
1305 closing = Some(response);
1306 }
1307 None => {
1308 command_channel_open = false;
1309 if let Ok(mut registry) = operations.lock() {
1310 let active = registry
1311 .records
1312 .values()
1313 .filter(|record| !record.state.terminal())
1314 .map(|record| record.id.clone())
1315 .collect::<Vec<_>>();
1316 for id in active {
1317 let _ = registry.cancel(&id);
1318 }
1319 }
1320 queued_operations.clear();
1321 if !operation_running {
1322 break;
1323 }
1324 },
1325 },
1326 _ = tick.tick() => {
1327 if let Some(workspace) = workspace.as_mut()
1328 && let Err(error) = workspace.tasks()
1329 {
1330 tracing::warn!(workspace_id, %error, "workspace task scheduler tick failed");
1331 }
1332 }
1333 }
1334 }
1335}
1336
1337fn workspace_event_batch(
1338 events: &VecDeque<DevelopmentDaemonEvent>,
1339 next_event: u64,
1340 dropped_events: u64,
1341 since: u64,
1342 limit: usize,
1343) -> Value {
1344 let oldest = events
1345 .front()
1346 .map(|event| event.sequence)
1347 .unwrap_or(next_event);
1348 let newest = events.back().map(|event| event.sequence).unwrap_or(0);
1349 let selected = events
1350 .iter()
1351 .filter(|event| event.sequence > since)
1352 .take(limit)
1353 .cloned()
1354 .collect::<Vec<_>>();
1355 serde_json::json!({
1356 "events": selected,
1357 "oldestSequence": oldest,
1358 "newestSequence": newest,
1359 "lostBefore": (since.saturating_add(1) < oldest).then_some(oldest),
1360 "droppedEvents": dropped_events,
1361 "capacity": WORKSPACE_EVENT_CAPACITY,
1362 })
1363}
1364
1365fn push_workspace_event(
1366 workspace_id: &str,
1367 events: &mut VecDeque<DevelopmentDaemonEvent>,
1368 next_event: &mut u64,
1369 dropped_events: &mut u64,
1370 kind: &str,
1371 tool_call_id: Option<String>,
1372 success: bool,
1373) {
1374 if events.len() == WORKSPACE_EVENT_CAPACITY {
1375 events.pop_front();
1376 *dropped_events = dropped_events.saturating_add(1);
1377 }
1378 events.push_back(DevelopmentDaemonEvent {
1379 sequence: *next_event,
1380 timestamp_ms: now_ms(),
1381 kind: kind.into(),
1382 workspace_id: workspace_id.into(),
1383 tool_call_id,
1384 success,
1385 });
1386 *next_event = next_event.saturating_add(1);
1387}
1388
1389fn daemon_event_kind(tool: &str) -> &'static str {
1390 if tool.starts_with("glass.agent.") {
1391 "agent.event"
1392 } else if tool.starts_with("glass.task.") {
1393 "task.changed"
1394 } else if tool.starts_with("glass.process.") {
1395 "process.output"
1396 } else if tool.starts_with("glass.browser.") || tool.starts_with("glass.web.") {
1397 "browser.revision"
1398 } else if tool.starts_with("glass.lsp.") {
1399 "lsp.diagnostics"
1400 } else if tool.starts_with("glass.debug.") {
1401 "debugger.stopped"
1402 } else if tool.starts_with("glass.test.") || tool.starts_with("glass.workflow.") {
1403 "test.completed"
1404 } else if tool.starts_with("glass.git.") {
1405 "git.changed"
1406 } else if tool.starts_with("glass.experiment.") {
1407 "experiment.changed"
1408 } else {
1409 "workspace.changed"
1410 }
1411}
1412
1413fn long_operation_tool(name: &str) -> bool {
1414 [
1415 "glass.process.",
1416 "glass.test.",
1417 "glass.eval.",
1418 "glass.debug.",
1419 "glass.git.",
1420 "glass.workflow.",
1421 "glass.experiment.",
1422 "glass.agent.",
1423 "glass.task.",
1424 "glass.browser.start",
1425 "glass.browser.stop",
1426 "glass.browser.reconnect",
1427 ]
1428 .iter()
1429 .any(|prefix| name.starts_with(prefix))
1430}
1431
1432fn inspect_workspace(
1433 workspace_id: &str,
1434 workspace: &mut DevelopmentWorkspace,
1435) -> Result<Value, String> {
1436 let agents = workspace
1437 .agents()
1438 .list()
1439 .map_err(|error| error.to_string())?;
1440 let tasks = workspace.tasks().map_err(|error| error.to_string())?;
1441 let processes = workspace
1442 .project_mut()
1443 .processes()
1444 .list_checked()
1445 .map_err(|error| error.to_string())?;
1446 Ok(serde_json::json!({
1447 "workspace":workspace_summary(workspace_id, workspace),
1448 "processes":processes,
1449 "agents":agents,
1450 "tasks":tasks,
1451 "kernels":workspace.kernels().snapshots().collect::<Vec<_>>(),
1452 "debuggers":workspace.debugger_names().collect::<Vec<_>>(),
1453 "browser":workspace.browser().state().map_err(|error| error.to_string())?
1454 }))
1455}
1456
1457#[cfg(unix)]
1458pub async fn request(
1459 socket: &Path,
1460 request: &DevelopmentDaemonRequest,
1461) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>> {
1462 let stream = tokio::net::UnixStream::connect(socket).await?;
1463 bounded_request_stream(stream, request).await
1464}
1465
1466#[cfg(windows)]
1467pub async fn request(
1468 socket: &Path,
1469 request: &DevelopmentDaemonRequest,
1470) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>> {
1471 use tokio::net::windows::named_pipe::ClientOptions;
1472 validate_windows_pipe_name(socket)?;
1473 let deadline = std::time::Instant::now() + Duration::from_secs(3);
1474 let pipe_name = socket.to_string_lossy();
1475 let stream = loop {
1476 match ClientOptions::new().open(pipe_name.as_ref()) {
1477 Ok(stream) => break stream,
1478 Err(error)
1479 if error.raw_os_error() == Some(231) && std::time::Instant::now() < deadline =>
1480 {
1481 tokio::time::sleep(Duration::from_millis(10)).await;
1482 }
1483 Err(error) => return Err(error.into()),
1484 }
1485 };
1486 bounded_request_stream(stream, request).await
1487}
1488
1489async fn bounded_request_stream<S>(
1490 stream: S,
1491 request: &DevelopmentDaemonRequest,
1492) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>>
1493where
1494 S: AsyncRead + AsyncWrite + Unpin,
1495{
1496 tokio::time::timeout(DAEMON_REQUEST_TIMEOUT, request_stream(stream, request))
1497 .await
1498 .map_err(|_| {
1499 format!(
1500 "daemon operation {} timed out after {} seconds",
1501 request.operation,
1502 DAEMON_REQUEST_TIMEOUT.as_secs()
1503 )
1504 })?
1505}
1506
1507async fn request_stream<S>(
1508 stream: S,
1509 request: &DevelopmentDaemonRequest,
1510) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>>
1511where
1512 S: AsyncRead + AsyncWrite + Unpin,
1513{
1514 let (read, mut write) = tokio::io::split(stream);
1515 let encoded = serde_json::to_vec(request)?;
1516 if encoded.len() > MAX_REQUEST_BYTES {
1517 return Err("daemon request exceeds the size limit".into());
1518 }
1519 write.write_all(&encoded).await?;
1520 write.write_all(b"\n").await?;
1521 write.flush().await?;
1522 let mut line = String::new();
1523 BufReader::new(read).read_line(&mut line).await?;
1524 Ok(serde_json::from_str(&line)?)
1525}
1526
1527#[cfg(not(any(unix, windows)))]
1528pub async fn request(
1529 _socket: &Path,
1530 _request: &DevelopmentDaemonRequest,
1531) -> Result<DevelopmentDaemonResponse, Box<dyn std::error::Error>> {
1532 Err("the local development daemon requires Unix-domain sockets on this platform".into())
1533}
1534
1535pub async fn forward_resident_tool_file(
1536 path: &Path,
1537 root: &Path,
1538 allow_mutation: bool,
1539 confirmed: bool,
1540) -> Result<Value, Box<dyn std::error::Error>> {
1541 let socket = PathBuf::from(
1542 std::env::var_os("GLASS_DEV_DAEMON_SOCKET")
1543 .ok_or("resident Pi broker socket is missing")?,
1544 );
1545 let token = std::env::var("GLASS_DEV_DAEMON_TOKEN")
1546 .map_err(|_| "resident Pi broker token is missing")?;
1547 let workspace_id = std::env::var("GLASS_DEV_DAEMON_WORKSPACE")
1548 .map_err(|_| "resident Pi broker workspace is missing")?;
1549 forward_resident_tool_file_with_context(
1550 &socket,
1551 &token,
1552 &workspace_id,
1553 path,
1554 root,
1555 allow_mutation,
1556 confirmed,
1557 )
1558 .await
1559}
1560
1561async fn forward_resident_tool_file_with_context(
1562 socket: &Path,
1563 token: &str,
1564 workspace_id: &str,
1565 path: &Path,
1566 root: &Path,
1567 allow_mutation: bool,
1568 confirmed: bool,
1569) -> Result<Value, Box<dyn std::error::Error>> {
1570 let call = read_private_tool_call(path)?;
1571 forward_resident_tool_call(
1572 socket,
1573 token,
1574 workspace_id,
1575 &call,
1576 root,
1577 allow_mutation,
1578 confirmed,
1579 )
1580 .await
1581}
1582
1583pub(crate) async fn forward_resident_tool_call_with_context(
1584 broker: &ResidentAgentBroker,
1585 call: &ToolCall,
1586 root: &Path,
1587 allow_mutation: bool,
1588 confirmed: bool,
1589) -> Result<Value, Box<dyn std::error::Error>> {
1590 forward_resident_tool_call(
1591 &broker.socket,
1592 &broker.token,
1593 &broker.workspace_id,
1594 call,
1595 root,
1596 allow_mutation,
1597 confirmed,
1598 )
1599 .await
1600}
1601
1602async fn forward_resident_tool_call(
1603 socket: &Path,
1604 token: &str,
1605 workspace_id: &str,
1606 call: &ToolCall,
1607 root: &Path,
1608 allow_mutation: bool,
1609 confirmed: bool,
1610) -> Result<Value, Box<dyn std::error::Error>> {
1611 let inspect = request(
1612 socket,
1613 &DevelopmentDaemonRequest {
1614 id: format!("inspect-{}", call.id),
1615 token: token.to_string(),
1616 operation: "workspace.inspect".into(),
1617 workspace_id: Some(workspace_id.to_string()),
1618 root: None,
1619 call: None,
1620 expected_generation: None,
1621 expected_project_revision: None,
1622 allow_mutation: false,
1623 confirmed: false,
1624 actor: Some("pi".into()),
1625 since: None,
1626 limit: None,
1627 operation_id: None,
1628 },
1629 )
1630 .await?;
1631 if !inspect.ok {
1632 return Err(inspect
1633 .error
1634 .unwrap_or_else(|| "workspace inspect failed".into())
1635 .into());
1636 }
1637 let expected_root = std::fs::canonicalize(root)?;
1638 let observed_root = inspect
1639 .result
1640 .pointer("/workspace/root")
1641 .and_then(Value::as_str);
1642 if observed_root != expected_root.to_str() {
1643 return Err("resident Pi broker root does not match the durable workspace".into());
1644 }
1645 let generation = inspect
1646 .result
1647 .pointer("/workspace/generation")
1648 .and_then(Value::as_u64)
1649 .ok_or("durable workspace generation is missing")?;
1650 let revision = inspect
1651 .result
1652 .pointer("/workspace/projectRevision")
1653 .and_then(Value::as_u64)
1654 .ok_or("durable workspace revision is missing")?;
1655 let mut response = request(
1656 socket,
1657 &DevelopmentDaemonRequest {
1658 id: format!("tool-{}", call.id),
1659 token: token.to_string(),
1660 operation: "operation.submit".into(),
1661 workspace_id: Some(workspace_id.to_string()),
1662 root: None,
1663 call: Some(call.clone()),
1664 expected_generation: Some(generation),
1665 expected_project_revision: Some(revision),
1666 allow_mutation,
1667 confirmed,
1668 actor: Some("pi".into()),
1669 since: None,
1670 limit: None,
1671 operation_id: None,
1672 },
1673 )
1674 .await?;
1675 if !response.ok {
1676 return Err(response
1677 .error
1678 .unwrap_or_else(|| "resident operation submission failed".into())
1679 .into());
1680 }
1681 let operation_id = response
1682 .result
1683 .pointer("/operation/id")
1684 .and_then(Value::as_str)
1685 .ok_or("daemon operation submission returned no operation ID")?
1686 .to_string();
1687 loop {
1688 let state = response
1689 .result
1690 .pointer("/operation/state")
1691 .and_then(Value::as_str);
1692 if state == Some("succeeded") {
1693 return response
1694 .result
1695 .pointer("/operation/result")
1696 .cloned()
1697 .ok_or_else(|| "successful daemon operation returned no result".into());
1698 }
1699 if matches!(state, Some("failed" | "cancelled" | "indeterminate")) {
1700 let reason = response
1701 .result
1702 .pointer("/operation/failureReason")
1703 .and_then(Value::as_str)
1704 .unwrap_or("resident operation did not succeed");
1705 return Err(reason.into());
1706 }
1707 tokio::time::sleep(Duration::from_millis(50)).await;
1708 response = request(
1709 socket,
1710 &DevelopmentDaemonRequest {
1711 id: format!("inspect-operation-{}", call.id),
1712 token: token.to_string(),
1713 operation: "operation.inspect".into(),
1714 workspace_id: Some(workspace_id.to_string()),
1715 root: None,
1716 call: None,
1717 expected_generation: None,
1718 expected_project_revision: None,
1719 allow_mutation: false,
1720 confirmed: false,
1721 actor: Some("pi".into()),
1722 since: None,
1723 limit: None,
1724 operation_id: Some(operation_id.clone()),
1725 },
1726 )
1727 .await?;
1728 if !response.ok {
1729 return Err(response
1730 .error
1731 .unwrap_or_else(|| "resident operation inspection failed".into())
1732 .into());
1733 }
1734 }
1735}
1736
1737pub(crate) fn read_private_tool_call(path: &Path) -> Result<ToolCall, Box<dyn std::error::Error>> {
1738 use std::io::Read;
1739 const MAX_CALL_BYTES: u64 = 256 * 1024;
1740 let canonical = path.canonicalize()?;
1741 let temporary_root = std::env::temp_dir().canonicalize()?;
1742 if canonical.parent() != Some(temporary_root.as_path())
1743 || !canonical
1744 .file_name()
1745 .and_then(|name| name.to_str())
1746 .is_some_and(|name| name.starts_with("glass-pi-call-") && name.ends_with(".json"))
1747 {
1748 return Err("Pi broker requests must use a private Glass temporary file".into());
1749 }
1750 let mut options = std::fs::OpenOptions::new();
1751 options.read(true);
1752 #[cfg(unix)]
1753 {
1754 use std::os::unix::fs::OpenOptionsExt;
1755 options.custom_flags(libc::O_NOFOLLOW);
1756 }
1757 let file = options.open(&canonical)?;
1758 let metadata = file.metadata()?;
1759 if !metadata.is_file() || metadata.len() > MAX_CALL_BYTES {
1760 return Err("invalid Pi broker request file".into());
1761 }
1762 #[cfg(unix)]
1763 {
1764 use std::os::unix::fs::{MetadataExt, PermissionsExt};
1765 if metadata.uid() != unsafe { libc::geteuid() }
1766 || metadata.permissions().mode() & 0o077 != 0
1767 {
1768 return Err("Pi broker request must be owned by this user with mode 0600".into());
1769 }
1770 }
1771 let mut encoded = Vec::with_capacity(metadata.len() as usize);
1772 file.take(MAX_CALL_BYTES + 1).read_to_end(&mut encoded)?;
1773 std::fs::remove_file(&canonical)?;
1774 if encoded.len() as u64 > MAX_CALL_BYTES {
1775 return Err("Pi broker request exceeds the size limit".into());
1776 }
1777 Ok(serde_json::from_slice(&encoded)?)
1778}
1779
1780fn workspace_summary(id: &str, workspace: &DevelopmentWorkspace) -> Value {
1781 serde_json::json!({
1782 "id":id,
1783 "root":workspace.root(),
1784 "trust":workspace.trust(),
1785 "generation":workspace.generation(),
1786 "projectRevision":workspace.project().revision()
1787 })
1788}
1789
1790fn validate_request(request: &DevelopmentDaemonRequest, token: &str) -> Result<(), String> {
1791 if request.token.as_bytes() != token.as_bytes() {
1792 return Err("invalid daemon authentication token".into());
1793 }
1794 validate_identifier(&request.id, "request")?;
1795 if request.operation.is_empty()
1796 || request.operation.len() > 128
1797 || request.operation.chars().any(char::is_control)
1798 {
1799 return Err("invalid daemon operation".into());
1800 }
1801 Ok(())
1802}
1803
1804fn required_workspace_id(request: &DevelopmentDaemonRequest) -> Result<&str, String> {
1805 let id = request
1806 .workspace_id
1807 .as_deref()
1808 .ok_or("daemon request requires workspaceId")?;
1809 validate_identifier(id, "workspace")?;
1810 Ok(id)
1811}
1812
1813fn required_operation_id(request: &DevelopmentDaemonRequest) -> Result<&str, String> {
1814 let id = request
1815 .operation_id
1816 .as_deref()
1817 .ok_or("daemon request requires operationId")?;
1818 validate_identifier(id, "operation")?;
1819 Ok(id)
1820}
1821
1822fn request_tool_context(
1823 request: &DevelopmentDaemonRequest,
1824 operation: &str,
1825) -> Result<DevelopmentToolContext, String> {
1826 let actor = request
1827 .actor
1828 .as_deref()
1829 .map(Actor::external)
1830 .unwrap_or_else(Actor::local);
1831 Ok(DevelopmentToolContext {
1832 authorization: ToolAuthorization {
1833 actor,
1834 allow_mutation: request.allow_mutation,
1835 confirmed: request.confirmed,
1836 },
1837 initiator: None,
1838 expected_generation: request
1839 .expected_generation
1840 .ok_or_else(|| format!("{operation} requires expectedGeneration"))?,
1841 expected_project_revision: request
1842 .expected_project_revision
1843 .ok_or_else(|| format!("{operation} requires expectedProjectRevision"))?,
1844 })
1845}
1846
1847fn validate_identifier(value: &str, description: &str) -> Result<(), String> {
1848 if value.is_empty()
1849 || value.len() > 128
1850 || !value
1851 .chars()
1852 .all(|character| character.is_ascii_alphanumeric() || "-_.".contains(character))
1853 {
1854 return Err(format!("invalid {description} identifier"));
1855 }
1856 Ok(())
1857}
1858
1859fn read_status(path: &Path) -> Result<DevelopmentDaemonStatus, Box<dyn std::error::Error>> {
1860 let bytes = std::fs::read(path)?;
1861 if bytes.len() > 64 * 1024 {
1862 return Err("daemon status exceeds the size limit".into());
1863 }
1864 Ok(serde_json::from_slice(&bytes)?)
1865}
1866
1867fn validate_status(
1868 status: &DevelopmentDaemonStatus,
1869 path: &Path,
1870) -> Result<(), Box<dyn std::error::Error>> {
1871 if status.protocol_version != PROTOCOL_VERSION || status.status_path != path {
1872 return Err("invalid development daemon status contract".into());
1873 }
1874 if status.workspace_count > MAX_WORKSPACES || status.client_count > MAX_CLIENTS {
1875 return Err("daemon status exceeds resource quotas".into());
1876 }
1877 Ok(())
1878}
1879
1880fn write_status(
1881 path: &Path,
1882 status: &DevelopmentDaemonStatus,
1883) -> Result<(), Box<dyn std::error::Error>> {
1884 let encoded = serde_json::to_vec_pretty(status)?;
1885 write_private(path, &encoded)
1886}
1887
1888fn update_counts(
1889 status_path: &Path,
1890 workspace_count: usize,
1891 client_count: usize,
1892) -> Result<(), Box<dyn std::error::Error>> {
1893 let mut status = read_status(status_path)?;
1894 status.workspace_count = workspace_count;
1895 status.client_count = client_count;
1896 write_status(status_path, &status)
1897}
1898
1899fn write_private(path: &Path, bytes: &[u8]) -> Result<(), Box<dyn std::error::Error>> {
1900 use std::io::Write;
1901 #[cfg(unix)]
1902 use std::os::unix::fs::OpenOptionsExt;
1903 let temporary = path.with_extension(format!("tmp-{}", std::process::id()));
1904 let mut options = std::fs::OpenOptions::new();
1905 options.create_new(true).write(true);
1906 #[cfg(unix)]
1907 options.mode(0o600);
1908 let mut file = options.open(&temporary)?;
1909 file.write_all(bytes)?;
1910 file.sync_all()?;
1911 std::fs::rename(temporary, path)?;
1912 Ok(())
1913}
1914
1915fn create_token() -> Result<String, Box<dyn std::error::Error>> {
1916 let mut bytes = [0_u8; 32];
1917 getrandom::fill(&mut bytes)?;
1918 Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
1919}
1920
1921fn token_path(status: &Path) -> PathBuf {
1922 status.with_extension("token")
1923}
1924
1925fn log_path(status: &Path) -> PathBuf {
1926 status.with_extension("log")
1927}
1928
1929fn bounded_log(status: &Path) -> Result<String, Box<dyn std::error::Error>> {
1930 use std::io::{Read, Seek, SeekFrom};
1931 let mut file = std::fs::File::open(log_path(status))?;
1932 let length = file.metadata()?.len();
1933 let start = length.saturating_sub(64 * 1024);
1934 file.seek(SeekFrom::Start(start))?;
1935 let mut output = String::new();
1936 file.read_to_string(&mut output)?;
1937 Ok(output)
1938}
1939
1940#[cfg(unix)]
1941fn authorize_local_peer(stream: &tokio::net::UnixStream) -> Result<(), Box<dyn std::error::Error>> {
1942 #[cfg(target_os = "linux")]
1943 {
1944 use std::os::fd::AsRawFd;
1945 let mut credentials = libc::ucred {
1946 pid: 0,
1947 uid: 0,
1948 gid: 0,
1949 };
1950 let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
1951 let result = unsafe {
1952 libc::getsockopt(
1953 stream.as_raw_fd(),
1954 libc::SOL_SOCKET,
1955 libc::SO_PEERCRED,
1956 (&mut credentials as *mut libc::ucred).cast(),
1957 &mut length,
1958 )
1959 };
1960 if result != 0 || credentials.uid != unsafe { libc::geteuid() } {
1961 return Err("daemon rejected a non-local-user peer".into());
1962 }
1963 }
1964 Ok(())
1965}
1966
1967#[cfg(unix)]
1968fn remove_socket_if_safe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
1969 use std::os::unix::fs::FileTypeExt;
1970 match std::fs::symlink_metadata(path) {
1971 Ok(metadata) if metadata.file_type().is_socket() => std::fs::remove_file(path)?,
1972 Ok(_) => return Err(format!("refusing to replace non-socket {}", path.display()).into()),
1973 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1974 Err(error) => return Err(error.into()),
1975 }
1976 Ok(())
1977}
1978
1979#[cfg(not(unix))]
1980fn remove_socket_if_safe(_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
1981 Ok(())
1982}
1983
1984fn process_alive(pid: u32) -> bool {
1985 #[cfg(unix)]
1986 {
1987 unsafe { libc::kill(pid as i32, 0) == 0 }
1988 }
1989 #[cfg(windows)]
1990 {
1991 use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
1992 use windows_sys::Win32::System::Threading::{
1993 GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
1994 };
1995 let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
1996 if process.is_null() {
1997 return false;
1998 }
1999 let mut exit_code = 0_u32;
2000 let success = unsafe { GetExitCodeProcess(process, &mut exit_code) } != 0;
2001 unsafe { CloseHandle(process) };
2002 success && exit_code == STILL_ACTIVE as u32
2003 }
2004 #[cfg(not(any(unix, windows)))]
2005 {
2006 let _ = pid;
2007 false
2008 }
2009}
2010
2011#[cfg(windows)]
2012fn validate_windows_pipe_name(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
2013 let value = path
2014 .to_str()
2015 .ok_or("Windows named-pipe endpoint must be Unicode")?;
2016 if !valid_windows_pipe_name(value) {
2017 return Err("invalid Windows Glass daemon pipe name".into());
2018 }
2019 Ok(())
2020}
2021
2022#[cfg(any(windows, test))]
2023fn valid_windows_pipe_name(value: &str) -> bool {
2024 value
2025 .strip_prefix(r"\\.\pipe\glass-dev-")
2026 .is_some_and(|name| {
2027 !name.is_empty()
2028 && name.len() <= 64
2029 && name
2030 .chars()
2031 .all(|character| character.is_ascii_alphanumeric() || character == '-')
2032 })
2033}
2034
2035fn effective_uid() -> u32 {
2036 #[cfg(unix)]
2037 {
2038 unsafe { libc::geteuid() }
2039 }
2040 #[cfg(not(unix))]
2041 {
2042 0
2043 }
2044}
2045
2046fn now_ms() -> u128 {
2047 SystemTime::now()
2048 .duration_since(UNIX_EPOCH)
2049 .unwrap_or_default()
2050 .as_millis()
2051}
2052
2053#[cfg(test)]
2054mod tests {
2055 use super::*;
2056 use std::sync::atomic::{AtomicU64, Ordering};
2057
2058 static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
2059
2060 #[test]
2061 fn windows_pipe_names_are_local_and_glass_owned() {
2062 assert!(valid_windows_pipe_name(
2063 r"\\.\pipe\glass-dev-0123456789abcdef"
2064 ));
2065 assert!(!valid_windows_pipe_name(r"\\server\pipe\glass-dev-test"));
2066 assert!(!valid_windows_pipe_name(r"\\.\pipe\other-product"));
2067 assert!(!valid_windows_pipe_name(r"\\.\pipe\glass-dev-bad/name"));
2068 }
2069
2070 fn test_context() -> DevelopmentToolContext {
2071 DevelopmentToolContext {
2072 authorization: ToolAuthorization {
2073 actor: Actor::external("daemon-concurrency-test"),
2074 allow_mutation: true,
2075 confirmed: true,
2076 },
2077 initiator: None,
2078 expected_generation: 1,
2079 expected_project_revision: 0,
2080 }
2081 }
2082
2083 async fn wait_for_operation_state(
2084 operations: &Arc<Mutex<OperationRegistry>>,
2085 operation_id: &str,
2086 expected: DevelopmentOperationState,
2087 ) {
2088 let deadline = std::time::Instant::now() + Duration::from_secs(5);
2089 loop {
2090 let state = operations.lock().unwrap().records[operation_id].state;
2091 if state == expected {
2092 return;
2093 }
2094 assert!(
2095 std::time::Instant::now() < deadline,
2096 "operation {operation_id} remained {state:?}, expected {expected:?}"
2097 );
2098 tokio::time::sleep(Duration::from_millis(10)).await;
2099 }
2100 }
2101
2102 async fn submit_and_wait(
2103 socket: &Path,
2104 request_value: &DevelopmentDaemonRequest,
2105 ) -> DevelopmentDaemonResponse {
2106 let mut submission = request_value.clone();
2107 submission.operation = "operation.submit".into();
2108 let accepted = request(socket, &submission).await.unwrap();
2109 if !accepted.ok {
2110 return accepted;
2111 }
2112 let operation_id = accepted.result["operation"]["id"]
2113 .as_str()
2114 .unwrap()
2115 .to_string();
2116 for sequence in 0..2_000 {
2117 let mut inspect = submission.clone();
2118 inspect.id = format!("inspect-{}-{sequence}", submission.id);
2119 inspect.operation = "operation.inspect".into();
2120 inspect.call = None;
2121 inspect.expected_generation = None;
2122 inspect.expected_project_revision = None;
2123 inspect.allow_mutation = false;
2124 inspect.confirmed = false;
2125 inspect.operation_id = Some(operation_id.clone());
2126 let response = request(socket, &inspect).await.unwrap();
2127 if !response.ok {
2128 return response;
2129 }
2130 match response.result["operation"]["state"].as_str() {
2131 Some("succeeded") => {
2132 return DevelopmentDaemonResponse {
2133 id: submission.id,
2134 ok: true,
2135 result: response.result["operation"]["result"].clone(),
2136 error: None,
2137 };
2138 }
2139 Some("failed" | "cancelled" | "indeterminate") => {
2140 return DevelopmentDaemonResponse {
2141 id: submission.id,
2142 ok: false,
2143 result: Value::Null,
2144 error: response.result["operation"]["failureReason"]
2145 .as_str()
2146 .map(str::to_string)
2147 .or_else(|| Some("operation did not succeed".into())),
2148 };
2149 }
2150 _ => tokio::time::sleep(Duration::from_millis(10)).await,
2151 }
2152 }
2153 DevelopmentDaemonResponse {
2154 id: submission.id,
2155 ok: false,
2156 result: Value::Null,
2157 error: Some("operation did not settle in the test deadline".into()),
2158 }
2159 }
2160
2161 #[tokio::test(flavor = "current_thread")]
2162 async fn workspace_actors_do_not_serialize_unrelated_long_operations() {
2163 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2164 let base = std::env::temp_dir().join(format!(
2165 "glassd-actor-concurrency-{}-{sequence}",
2166 std::process::id()
2167 ));
2168 let first_root = base.join("first");
2169 let second_root = base.join("second");
2170 std::fs::create_dir_all(&first_root).unwrap();
2171 std::fs::create_dir_all(&second_root).unwrap();
2172 for root in [&first_root, &second_root] {
2173 std::fs::write(
2174 root.join("Cargo.toml"),
2175 "[package]\nname='stress-fixture'\nversion='0.1.0'\n",
2176 )
2177 .unwrap();
2178 }
2179 let dap_adapter = second_root.join("stress_dap.py");
2180 std::fs::write(
2181 &dap_adapter,
2182 r#"import json, sys
2183while True:
2184 line = sys.stdin.buffer.readline()
2185 if not line:
2186 break
2187 if not line.lower().startswith(b'content-length:'):
2188 continue
2189 length = int(line.split(b':', 1)[1])
2190 while sys.stdin.buffer.readline() not in (b'\r\n', b'\n', b''):
2191 pass
2192 request = json.loads(sys.stdin.buffer.read(length))
2193 response = {'seq': request['seq'] + 1000, 'type': 'response', 'request_seq': request['seq'], 'command': request['command'], 'success': True, 'body': {}}
2194 body = json.dumps(response).encode()
2195 sys.stdout.buffer.write(f'Content-Length: {len(body)}\r\n\r\n'.encode() + body)
2196 sys.stdout.buffer.flush()
2197"#,
2198 )
2199 .unwrap();
2200 let store = WorkspaceTrustStore::at(base.join("trust.json"));
2201 for root in [&first_root, &second_root] {
2202 store
2203 .trust_project(&crate::WorkspaceIdentity::inspect(root).unwrap())
2204 .unwrap();
2205 }
2206 let local = tokio::task::LocalSet::new();
2207 local
2208 .run_until(async {
2209 let actor = |id: &str, root: &Path| {
2210 let workspace =
2211 DevelopmentWorkspace::open_with_store(root, store.clone()).unwrap();
2212 let summary = workspace_summary(id, &workspace);
2213 let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2214 let operations = Arc::new(Mutex::new(OperationRegistry::new(id.into())));
2215 tokio::task::spawn_local(run_workspace_actor(
2216 id.into(),
2217 workspace,
2218 receiver,
2219 Arc::clone(&operations),
2220 ));
2221 WorkspaceActorHandle {
2222 sender,
2223 summary,
2224 operations,
2225 }
2226 };
2227 let first = actor("first", &first_root);
2228 let second = actor("second", &second_root);
2229 let python = ["python3", "python"]
2230 .into_iter()
2231 .find(|program| {
2232 std::process::Command::new(program)
2233 .arg("--version")
2234 .output()
2235 .is_ok_and(|output| output.status.success())
2236 })
2237 .expect("full-suite stress requires Python for the fixture DAP adapter");
2238 workspace_tool(
2239 second.clone(),
2240 ToolCall {
2241 id: "debug-start".into(),
2242 name: "glass.debug.start".into(),
2243 arguments: serde_json::json!({
2244 "session":"stress",
2245 "command":python,
2246 "arguments":[dap_adapter],
2247 "timeoutSeconds":3
2248 }),
2249 },
2250 test_context(),
2251 )
2252 .await
2253 .unwrap();
2254 let (kernel_kind, kernel_code) = if cfg!(windows) {
2255 ("python", "import time; time.sleep(3); print('complete')")
2256 } else {
2257 ("shell", "sleep 3; echo complete")
2258 };
2259 workspace_tool(
2260 first.clone(),
2261 ToolCall {
2262 id: "shell-start".into(),
2263 name: "glass.eval.start".into(),
2264 arguments: serde_json::json!({"name":"slow","kind":kernel_kind}),
2265 },
2266 test_context(),
2267 )
2268 .await
2269 .unwrap();
2270 let slow = tokio::task::spawn_local(workspace_tool(
2271 first.clone(),
2272 ToolCall {
2273 id: "shell-slow".into(),
2274 name: "glass.eval.execute".into(),
2275 arguments: serde_json::json!({
2276 "name":"slow",
2277 "code":kernel_code,
2278 "timeoutSeconds":5
2279 }),
2280 },
2281 test_context(),
2282 ));
2283 tokio::time::sleep(Duration::from_millis(50)).await;
2284 let (inspect, browser, lsp, debug, tests, processes) = tokio::join!(
2285 workspace_inspect(second.clone()),
2286 workspace_tool(
2287 second.clone(),
2288 ToolCall {
2289 id: "browser-state".into(),
2290 name: "glass.browser.state".into(),
2291 arguments: serde_json::json!({}),
2292 },
2293 test_context(),
2294 ),
2295 workspace_tool(
2296 second.clone(),
2297 ToolCall {
2298 id: "lsp-list".into(),
2299 name: "glass.lsp.list".into(),
2300 arguments: serde_json::json!({}),
2301 },
2302 test_context(),
2303 ),
2304 workspace_tool(
2305 second.clone(),
2306 ToolCall {
2307 id: "debug-events".into(),
2308 name: "glass.debug.events".into(),
2309 arguments: serde_json::json!({"session":"stress"}),
2310 },
2311 test_context(),
2312 ),
2313 workspace_tool(
2314 second.clone(),
2315 ToolCall {
2316 id: "test-discover".into(),
2317 name: "glass.test.discover".into(),
2318 arguments: serde_json::json!({}),
2319 },
2320 test_context(),
2321 ),
2322 workspace_tool(
2323 second.clone(),
2324 ToolCall {
2325 id: "process-list".into(),
2326 name: "glass.process.list".into(),
2327 arguments: serde_json::json!({}),
2328 },
2329 test_context(),
2330 ),
2331 );
2332 let inspect = inspect.unwrap();
2333 assert_eq!(inspect["workspace"]["id"], "second");
2334 assert!(browser.is_ok());
2335 assert!(lsp.is_ok());
2336 assert!(debug.is_ok());
2337 assert!(tests.is_ok());
2338 assert!(processes.is_ok());
2339 assert!(
2340 !slow.is_finished(),
2341 "unrelated workspace work waited for the slow operation"
2342 );
2343 assert!(slow.await.unwrap().is_ok());
2344 for handle in [first, second] {
2345 let (response, received) = tokio::sync::oneshot::channel();
2346 handle
2347 .sender
2348 .send(WorkspaceCommand::Shutdown { response })
2349 .await
2350 .unwrap();
2351 received.await.unwrap();
2352 }
2353 })
2354 .await;
2355 std::fs::remove_dir_all(base).unwrap();
2356 }
2357
2358 #[tokio::test(flavor = "current_thread")]
2359 async fn long_operations_reconnect_reconcile_and_cancel_by_stable_id() {
2360 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2361 let root = std::env::temp_dir().join(format!(
2362 "glassd-operation-lifecycle-{}-{sequence}",
2363 std::process::id()
2364 ));
2365 std::fs::create_dir_all(&root).unwrap();
2366 let store = WorkspaceTrustStore::at(root.join("trust.json"));
2367 store
2368 .trust_project(&crate::WorkspaceIdentity::inspect(&root).unwrap())
2369 .unwrap();
2370 let local = tokio::task::LocalSet::new();
2371 local
2372 .run_until(async {
2373 let workspace =
2374 DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
2375 let summary = workspace_summary("operations", &workspace);
2376 let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2377 let operations = Arc::new(Mutex::new(OperationRegistry::new("operations".into())));
2378 tokio::task::spawn_local(run_workspace_actor(
2379 "operations".into(),
2380 workspace,
2381 receiver,
2382 Arc::clone(&operations),
2383 ));
2384 let handle = WorkspaceActorHandle {
2385 sender: sender.clone(),
2386 summary: summary.clone(),
2387 operations: Arc::clone(&operations),
2388 };
2389 let (kernel_kind, slow_code) = if cfg!(windows) {
2390 ("python", "import time; time.sleep(0.2); print('complete')")
2391 } else {
2392 ("shell", "sleep 0.2; echo complete")
2393 };
2394 workspace_tool(
2395 handle.clone(),
2396 ToolCall {
2397 id: "operation-kernel-start".into(),
2398 name: "glass.eval.start".into(),
2399 arguments: serde_json::json!({"name":"operation","kind":kernel_kind}),
2400 },
2401 test_context(),
2402 )
2403 .await
2404 .unwrap();
2405
2406 let (first, created) = operations
2407 .lock()
2408 .unwrap()
2409 .submit(
2410 "stable-request",
2411 "test-client".into(),
2412 "glass.eval.execute".into(),
2413 0,
2414 true,
2415 )
2416 .unwrap();
2417 assert!(created);
2418 sender
2419 .send(WorkspaceCommand::SubmitOperation {
2420 operation_id: first.id.clone(),
2421 call: ToolCall {
2422 id: "operation-slow".into(),
2423 name: "glass.eval.execute".into(),
2424 arguments: serde_json::json!({
2425 "name":"operation",
2426 "code":slow_code,
2427 "timeoutSeconds":2
2428 }),
2429 },
2430 context: Box::new(test_context()),
2431 })
2432 .await
2433 .unwrap();
2434
2435 let reconnected = WorkspaceActorHandle {
2437 sender: sender.clone(),
2438 summary,
2439 operations: Arc::clone(&operations),
2440 };
2441 let immediate = reconnected.operations.lock().unwrap().records[&first.id].clone();
2442 assert!(matches!(
2443 immediate.state,
2444 DevelopmentOperationState::Queued | DevelopmentOperationState::Running
2445 ));
2446 let duplicate = operations
2447 .lock()
2448 .unwrap()
2449 .submit(
2450 "stable-request",
2451 "test-client".into(),
2452 "glass.eval.execute".into(),
2453 0,
2454 true,
2455 )
2456 .unwrap();
2457 assert!(!duplicate.1);
2458 assert_eq!(duplicate.0.id, first.id);
2459 wait_for_operation_state(
2460 &operations,
2461 &first.id,
2462 DevelopmentOperationState::Succeeded,
2463 )
2464 .await;
2465 let finished = operations.lock().unwrap().records[&first.id].clone();
2466 assert_eq!(finished.state, DevelopmentOperationState::Succeeded);
2467 assert!(finished.result.is_some());
2468 assert_eq!(finished.revision_after, Some(0));
2469
2470 let (cancelled, _) = operations
2471 .lock()
2472 .unwrap()
2473 .submit(
2474 "cancel-request",
2475 "test-client".into(),
2476 "glass.eval.execute".into(),
2477 0,
2478 true,
2479 )
2480 .unwrap();
2481 sender
2482 .send(WorkspaceCommand::SubmitOperation {
2483 operation_id: cancelled.id.clone(),
2484 call: ToolCall {
2485 id: "operation-cancel".into(),
2486 name: "glass.eval.execute".into(),
2487 arguments: serde_json::json!({
2488 "name":"operation",
2489 "code":if cfg!(windows) {
2490 "import time; time.sleep(2); print('cancel')"
2491 } else {
2492 "sleep 2; echo cancel"
2493 },
2494 "timeoutSeconds":5
2495 }),
2496 },
2497 context: Box::new(test_context()),
2498 })
2499 .await
2500 .unwrap();
2501 wait_for_operation_state(
2502 &operations,
2503 &cancelled.id,
2504 DevelopmentOperationState::Running,
2505 )
2506 .await;
2507 let cancelling = operations.lock().unwrap().cancel(&cancelled.id).unwrap();
2508 assert!(cancelling.cancellation_requested);
2509 wait_for_operation_state(
2510 &operations,
2511 &cancelled.id,
2512 DevelopmentOperationState::Cancelled,
2513 )
2514 .await;
2515 assert_eq!(
2516 operations.lock().unwrap().records[&cancelled.id].state,
2517 DevelopmentOperationState::Cancelled
2518 );
2519 assert!(
2520 operations
2521 .lock()
2522 .unwrap()
2523 .events
2524 .iter()
2525 .any(|event| event.operation_id == first.id
2526 && event.state == DevelopmentOperationState::Succeeded)
2527 );
2528
2529 let (response, received) = tokio::sync::oneshot::channel();
2530 reconnected
2531 .sender
2532 .send(WorkspaceCommand::Shutdown { response })
2533 .await
2534 .unwrap();
2535 received.await.unwrap();
2536 })
2537 .await;
2538 std::fs::remove_dir_all(root).unwrap();
2539 }
2540
2541 #[tokio::test(flavor = "current_thread")]
2542 async fn workspace_event_cursors_survive_client_reconnects() {
2543 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2544 let root = std::env::temp_dir().join(format!(
2545 "glassd-event-cursor-{}-{sequence}",
2546 std::process::id()
2547 ));
2548 std::fs::create_dir_all(&root).unwrap();
2549 let local = tokio::task::LocalSet::new();
2550 local
2551 .run_until(async {
2552 let workspace = DevelopmentWorkspace::open(&root).unwrap();
2553 let summary = workspace_summary("events", &workspace);
2554 let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2555 let operations = Arc::new(Mutex::new(OperationRegistry::new("events".into())));
2556 tokio::task::spawn_local(run_workspace_actor(
2557 "events".into(),
2558 workspace,
2559 receiver,
2560 Arc::clone(&operations),
2561 ));
2562 let first_client = WorkspaceActorHandle {
2563 sender: sender.clone(),
2564 summary: summary.clone(),
2565 operations: Arc::clone(&operations),
2566 };
2567 workspace_tool(
2568 first_client,
2569 ToolCall {
2570 id: "task-list".into(),
2571 name: "glass.task.list".into(),
2572 arguments: serde_json::json!({}),
2573 },
2574 test_context(),
2575 )
2576 .await
2577 .unwrap();
2578 let first = workspace_events(
2579 WorkspaceActorHandle {
2580 sender: sender.clone(),
2581 summary: summary.clone(),
2582 operations: Arc::clone(&operations),
2583 },
2584 0,
2585 16,
2586 )
2587 .await
2588 .unwrap();
2589 assert_eq!(first["events"][0]["kind"], "workspace.opened");
2590 assert_eq!(first["events"][1]["kind"], "task.changed");
2591 let cursor = first["newestSequence"].as_u64().unwrap();
2592
2593 let reconnected = WorkspaceActorHandle {
2595 sender,
2596 summary,
2597 operations,
2598 };
2599 workspace_tool(
2600 reconnected.clone(),
2601 ToolCall {
2602 id: "task-list-after-reconnect".into(),
2603 name: "glass.task.list".into(),
2604 arguments: serde_json::json!({}),
2605 },
2606 test_context(),
2607 )
2608 .await
2609 .unwrap();
2610 let resumed = workspace_events(reconnected, cursor, 16).await.unwrap();
2611 assert_eq!(resumed["events"].as_array().unwrap().len(), 1);
2612 assert_eq!(resumed["events"][0]["kind"], "task.changed");
2613 assert_eq!(resumed["lostBefore"], Value::Null);
2614 })
2615 .await;
2616 std::fs::remove_dir_all(root).unwrap();
2617 }
2618
2619 #[test]
2620 fn workspace_event_overflow_is_bounded_and_observable() {
2621 let mut events = VecDeque::with_capacity(WORKSPACE_EVENT_CAPACITY);
2622 let mut next = 1;
2623 let mut dropped = 0;
2624 for index in 0..=WORKSPACE_EVENT_CAPACITY {
2625 push_workspace_event(
2626 "bounded",
2627 &mut events,
2628 &mut next,
2629 &mut dropped,
2630 "workspace.changed",
2631 Some(format!("call-{index}")),
2632 true,
2633 );
2634 }
2635 let batch = workspace_event_batch(&events, next, dropped, 0, MAX_EVENT_BATCH);
2636 assert_eq!(events.len(), WORKSPACE_EVENT_CAPACITY);
2637 assert_eq!(batch["droppedEvents"], 1);
2638 assert_eq!(batch["lostBefore"], 2);
2639 assert_eq!(batch["events"].as_array().unwrap().len(), MAX_EVENT_BATCH);
2640 }
2641
2642 #[tokio::test(flavor = "current_thread")]
2643 #[cfg(unix)]
2644 async fn daemon_preserves_resources_across_client_disconnects() {
2645 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2646 let base =
2647 std::env::temp_dir().join(format!("glassd-test-{}-{sequence}", std::process::id()));
2648 let project = base.join("project");
2649 std::fs::create_dir_all(&project).unwrap();
2650 std::fs::write(
2651 project.join("Cargo.toml"),
2652 "[package]\nname='x'\nversion='0.1.0'\n",
2653 )
2654 .unwrap();
2655 let trust_store = WorkspaceTrustStore::at(base.join("trust.json"));
2656 trust_store
2657 .trust_project(&crate::WorkspaceIdentity::inspect(&project).unwrap())
2658 .unwrap();
2659 let socket = base.join("glassd.sock");
2660 let status = base.join("glassd.json");
2661 let local = tokio::task::LocalSet::new();
2662 local
2663 .run_until(async {
2664 let server_socket = socket.clone();
2665 let server_status = status.clone();
2666 let server_trust_store = trust_store.clone();
2667 let server = tokio::task::spawn_local(async move {
2668 serve_with_store(&server_socket, &server_status, server_trust_store)
2669 .await
2670 .unwrap()
2671 });
2672 for _ in 0..100 {
2673 if status.exists() && socket.exists() {
2674 break;
2675 }
2676 tokio::time::sleep(Duration::from_millis(10)).await;
2677 }
2678 let token = std::fs::read_to_string(token_path(&status)).unwrap();
2679 let base_request = |id: &str, operation: &str| DevelopmentDaemonRequest {
2680 id: id.into(),
2681 token: token.clone(),
2682 operation: operation.into(),
2683 workspace_id: Some("fixture".into()),
2684 root: None,
2685 call: None,
2686 expected_generation: None,
2687 expected_project_revision: None,
2688 allow_mutation: false,
2689 confirmed: false,
2690 actor: Some("test-client".into()),
2691 since: None,
2692 limit: None,
2693 operation_id: None,
2694 };
2695 let mut open = base_request("open", "workspace.open");
2696 open.root = Some(project.clone());
2697 assert!(request(&socket, &open).await.unwrap().ok);
2698 let mut start = base_request("start", "operation.submit");
2699 start.call = Some(ToolCall {
2700 id: "kernel-start".into(),
2701 name: "glass.eval.start".into(),
2702 arguments: serde_json::json!({"name":"durable","kind":"sql"}),
2703 });
2704 start.expected_generation = Some(1);
2705 start.expected_project_revision = Some(0);
2706 start.allow_mutation = true;
2707 start.confirmed = true;
2708 assert!(submit_and_wait(&socket, &start).await.ok);
2709 let mut process_start = base_request("process-start", "operation.submit");
2710 process_start.call = Some(ToolCall {
2711 id: "process-start".into(),
2712 name: "glass.process.start".into(),
2713 arguments: serde_json::json!({"name":"durable-process","command":"sleep 30"}),
2714 });
2715 process_start.expected_generation = Some(1);
2716 process_start.expected_project_revision = Some(0);
2717 process_start.allow_mutation = true;
2718 process_start.confirmed = true;
2719 assert!(submit_and_wait(&socket, &process_start).await.ok);
2720 let pi_available = std::process::Command::new("pi")
2721 .arg("--version")
2722 .output()
2723 .is_ok();
2724 if pi_available {
2725 let mut agent_start = base_request("agent-start", "operation.submit");
2726 agent_start.call = Some(ToolCall {
2727 id: "agent-start".into(),
2728 name: "glass.agent.spawn".into(),
2729 arguments: serde_json::json!({"spec":{
2730 "role":"durability-probe",
2731 "task":"Remain idle while the client reconnects",
2732 "dependencies":[],
2733 "model":null,
2734 "thinking":null,
2735 "worktree":null,
2736 "unrestricted":false,
2737 "maxRuntimeSeconds":60,
2738 "maxEvents":100
2739 }}),
2740 });
2741 agent_start.expected_generation = Some(1);
2742 agent_start.expected_project_revision = Some(1);
2743 agent_start.allow_mutation = true;
2744 agent_start.confirmed = true;
2745 let agent_response = submit_and_wait(&socket, &agent_start).await;
2746 assert!(agent_response.ok, "{:?}", agent_response.error);
2747 }
2748 let browser_e2e = std::env::var("GLASS_E2E").as_deref() == Ok("1")
2749 && std::env::var_os("GLASS_CHROME_PATH").is_some();
2750 if browser_e2e {
2751 let port_probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2752 let browser_port = port_probe.local_addr().unwrap().port();
2753 drop(port_probe);
2754 let mut browser_start = base_request("browser-start", "operation.submit");
2755 browser_start.call = Some(ToolCall {
2756 id: "browser-start".into(),
2757 name: "glass.browser.start".into(),
2758 arguments: serde_json::json!({
2759 "port":browser_port,
2760 "incognito":true,
2761 "chromePath":std::env::var("GLASS_CHROME_PATH").unwrap()
2762 }),
2763 });
2764 browser_start.expected_generation = Some(1);
2765 browser_start.expected_project_revision = Some(1);
2766 browser_start.allow_mutation = true;
2767 browser_start.confirmed = true;
2768 let response = submit_and_wait(&socket, &browser_start).await;
2769 assert!(response.ok, "{:?}", response.error);
2770 }
2771 let call = ToolCall {
2774 id: "kernel-execute".into(),
2775 name: "glass.eval.execute".into(),
2776 arguments: serde_json::json!({"name":"durable","code":"SELECT 42 AS answer"}),
2777 };
2778 let call_path = std::env::temp_dir().join(format!(
2779 "glass-pi-call-{}-{sequence}.json",
2780 std::process::id()
2781 ));
2782 write_private(&call_path, &serde_json::to_vec(&call).unwrap()).unwrap();
2783 let result = forward_resident_tool_file_with_context(
2784 &socket, &token, "fixture", &call_path, &project, true, true,
2785 )
2786 .await
2787 .unwrap();
2788 assert_eq!(result["value"][0]["answer"], 42);
2789 let inspect = request(
2792 &socket,
2793 &base_request("inspect-reconnected", "workspace.inspect"),
2794 )
2795 .await
2796 .unwrap();
2797 assert!(inspect.ok);
2798 assert!(
2799 inspect.result["processes"]
2800 .as_array()
2801 .unwrap()
2802 .iter()
2803 .any(|process| process["name"] == "durable-process")
2804 );
2805 assert!(
2806 inspect.result["kernels"]
2807 .as_array()
2808 .unwrap()
2809 .iter()
2810 .any(|kernel| kernel["name"] == "durable")
2811 );
2812 if pi_available {
2813 assert!(!inspect.result["agents"].as_array().unwrap().is_empty());
2814 }
2815 assert_eq!(inspect.result["browser"]["connected"], browser_e2e);
2816 let mut process_stop = base_request("process-stop", "operation.submit");
2817 process_stop.call = Some(ToolCall {
2818 id: "process-stop".into(),
2819 name: "glass.process.stop".into(),
2820 arguments: serde_json::json!({"name":"durable-process"}),
2821 });
2822 process_stop.expected_generation = Some(1);
2823 process_stop.expected_project_revision = Some(1);
2824 process_stop.allow_mutation = true;
2825 process_stop.confirmed = true;
2826 assert!(submit_and_wait(&socket, &process_stop).await.ok);
2827 if browser_e2e {
2828 let mut browser_stop = base_request("browser-stop", "operation.submit");
2829 browser_stop.call = Some(ToolCall {
2830 id: "browser-stop".into(),
2831 name: "glass.browser.stop".into(),
2832 arguments: serde_json::json!({}),
2833 });
2834 browser_stop.expected_generation = Some(1);
2835 browser_stop.expected_project_revision = Some(2);
2836 browser_stop.allow_mutation = true;
2837 browser_stop.confirmed = true;
2838 assert!(submit_and_wait(&socket, &browser_stop).await.ok);
2839 }
2840 server.abort();
2841 })
2842 .await;
2843 let _ = std::fs::remove_dir_all(base);
2844 }
2845
2846 #[tokio::test(flavor = "current_thread")]
2847 #[cfg(unix)]
2848 async fn daemon_reconnect_preserves_untrusted_state_and_cannot_elevate_it() {
2849 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2850 let base = std::env::temp_dir().join(format!(
2851 "glassd-trust-test-{}-{sequence}",
2852 std::process::id()
2853 ));
2854 let project = base.join("project");
2855 std::fs::create_dir_all(&project).unwrap();
2856 std::fs::write(
2857 project.join("glass.toml"),
2858 "[tools.hostile]\ndescription='hostile'\ncommand='echo unsafe'\n",
2859 )
2860 .unwrap();
2861 let socket = base.join("glassd.sock");
2862 let status = base.join("glassd.json");
2863 let local = tokio::task::LocalSet::new();
2864 local
2865 .run_until(async {
2866 let server_socket = socket.clone();
2867 let server_status = status.clone();
2868 let store = WorkspaceTrustStore::at(base.join("trust.json"));
2869 let server = tokio::task::spawn_local(async move {
2870 serve_with_store(&server_socket, &server_status, store)
2871 .await
2872 .unwrap()
2873 });
2874 for _ in 0..100 {
2875 if status.exists() && socket.exists() {
2876 break;
2877 }
2878 tokio::time::sleep(Duration::from_millis(10)).await;
2879 }
2880 let token = std::fs::read_to_string(token_path(&status)).unwrap();
2881 let base_request = |id: &str, operation: &str| DevelopmentDaemonRequest {
2882 id: id.into(),
2883 token: token.clone(),
2884 operation: operation.into(),
2885 workspace_id: Some("untrusted".into()),
2886 root: None,
2887 call: None,
2888 expected_generation: None,
2889 expected_project_revision: None,
2890 allow_mutation: false,
2891 confirmed: false,
2892 actor: Some("external-agent".into()),
2893 since: None,
2894 limit: None,
2895 operation_id: None,
2896 };
2897 let mut open = base_request("open", "workspace.open");
2898 open.root = Some(project.clone());
2899 let opened = request(&socket, &open).await.unwrap();
2900 assert!(opened.ok);
2901 assert_eq!(opened.result["trust"], "untrusted");
2902
2903 let inspected = request(&socket, &base_request("inspect", "workspace.inspect"))
2906 .await
2907 .unwrap();
2908 assert!(inspected.ok);
2909 assert_eq!(inspected.result["workspace"]["trust"], "untrusted");
2910
2911 let mut tool = base_request("tool", "operation.submit");
2912 tool.call = Some(ToolCall {
2913 id: "hostile".into(),
2914 name: "glass.custom.hostile".into(),
2915 arguments: serde_json::json!({}),
2916 });
2917 tool.expected_generation = Some(1);
2918 tool.expected_project_revision = Some(0);
2919 tool.allow_mutation = true;
2920 tool.confirmed = true;
2921 let denied = submit_and_wait(&socket, &tool).await;
2922 assert!(!denied.ok);
2923 assert!(denied.error.unwrap().contains("trust"));
2924 server.abort();
2925 })
2926 .await;
2927 let _ = std::fs::remove_dir_all(base);
2928 }
2929
2930 #[test]
2931 fn daemon_identifiers_and_status_quotas_fail_closed() {
2932 assert!(validate_identifier("workspace-1", "workspace").is_ok());
2933 assert!(validate_identifier("../escape", "workspace").is_err());
2934 }
2935}