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
1929pub fn log_tail(status_path: Option<&Path>) -> Result<String, Box<dyn std::error::Error>> {
1930 let (_, default_status) = default_paths();
1931 bounded_log(status_path.unwrap_or(&default_status))
1932}
1933
1934fn bounded_log(status: &Path) -> Result<String, Box<dyn std::error::Error>> {
1935 use std::io::{Read, Seek, SeekFrom};
1936 let mut file = std::fs::File::open(log_path(status))?;
1937 let length = file.metadata()?.len();
1938 let start = length.saturating_sub(64 * 1024);
1939 file.seek(SeekFrom::Start(start))?;
1940 let mut output = String::new();
1941 file.read_to_string(&mut output)?;
1942 Ok(output)
1943}
1944
1945#[cfg(unix)]
1946fn authorize_local_peer(
1947 _stream: &tokio::net::UnixStream,
1948) -> Result<(), Box<dyn std::error::Error>> {
1949 #[cfg(target_os = "linux")]
1950 {
1951 use std::os::fd::AsRawFd;
1952 let mut credentials = libc::ucred {
1953 pid: 0,
1954 uid: 0,
1955 gid: 0,
1956 };
1957 let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
1958 let result = unsafe {
1959 libc::getsockopt(
1960 _stream.as_raw_fd(),
1961 libc::SOL_SOCKET,
1962 libc::SO_PEERCRED,
1963 (&mut credentials as *mut libc::ucred).cast(),
1964 &mut length,
1965 )
1966 };
1967 if result != 0 || credentials.uid != unsafe { libc::geteuid() } {
1968 return Err("daemon rejected a non-local-user peer".into());
1969 }
1970 }
1971 Ok(())
1972}
1973
1974#[cfg(unix)]
1975fn remove_socket_if_safe(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
1976 use std::os::unix::fs::FileTypeExt;
1977 match std::fs::symlink_metadata(path) {
1978 Ok(metadata) if metadata.file_type().is_socket() => std::fs::remove_file(path)?,
1979 Ok(_) => return Err(format!("refusing to replace non-socket {}", path.display()).into()),
1980 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
1981 Err(error) => return Err(error.into()),
1982 }
1983 Ok(())
1984}
1985
1986#[cfg(not(unix))]
1987fn remove_socket_if_safe(_path: &Path) -> Result<(), Box<dyn std::error::Error>> {
1988 Ok(())
1989}
1990
1991fn process_alive(pid: u32) -> bool {
1992 #[cfg(unix)]
1993 {
1994 unsafe { libc::kill(pid as i32, 0) == 0 }
1995 }
1996 #[cfg(windows)]
1997 {
1998 use windows_sys::Win32::Foundation::{CloseHandle, STILL_ACTIVE};
1999 use windows_sys::Win32::System::Threading::{
2000 GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
2001 };
2002 let process = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };
2003 if process.is_null() {
2004 return false;
2005 }
2006 let mut exit_code = 0_u32;
2007 let success = unsafe { GetExitCodeProcess(process, &mut exit_code) } != 0;
2008 unsafe { CloseHandle(process) };
2009 success && exit_code == STILL_ACTIVE as u32
2010 }
2011 #[cfg(not(any(unix, windows)))]
2012 {
2013 let _ = pid;
2014 false
2015 }
2016}
2017
2018#[cfg(windows)]
2019fn validate_windows_pipe_name(path: &Path) -> Result<(), Box<dyn std::error::Error>> {
2020 let value = path
2021 .to_str()
2022 .ok_or("Windows named-pipe endpoint must be Unicode")?;
2023 if !valid_windows_pipe_name(value) {
2024 return Err("invalid Windows Glass daemon pipe name".into());
2025 }
2026 Ok(())
2027}
2028
2029#[cfg(any(windows, test))]
2030fn valid_windows_pipe_name(value: &str) -> bool {
2031 value
2032 .strip_prefix(r"\\.\pipe\glass-dev-")
2033 .is_some_and(|name| {
2034 !name.is_empty()
2035 && name.len() <= 64
2036 && name
2037 .chars()
2038 .all(|character| character.is_ascii_alphanumeric() || character == '-')
2039 })
2040}
2041
2042fn effective_uid() -> u32 {
2043 #[cfg(unix)]
2044 {
2045 unsafe { libc::geteuid() }
2046 }
2047 #[cfg(not(unix))]
2048 {
2049 0
2050 }
2051}
2052
2053fn now_ms() -> u128 {
2054 SystemTime::now()
2055 .duration_since(UNIX_EPOCH)
2056 .unwrap_or_default()
2057 .as_millis()
2058}
2059
2060#[cfg(test)]
2061mod tests {
2062 use super::*;
2063 use std::sync::atomic::{AtomicU64, Ordering};
2064
2065 static NEXT_ROOT: AtomicU64 = AtomicU64::new(0);
2066
2067 #[test]
2068 fn windows_pipe_names_are_local_and_glass_owned() {
2069 assert!(valid_windows_pipe_name(
2070 r"\\.\pipe\glass-dev-0123456789abcdef"
2071 ));
2072 assert!(!valid_windows_pipe_name(r"\\server\pipe\glass-dev-test"));
2073 assert!(!valid_windows_pipe_name(r"\\.\pipe\other-product"));
2074 assert!(!valid_windows_pipe_name(r"\\.\pipe\glass-dev-bad/name"));
2075 }
2076
2077 fn test_context() -> DevelopmentToolContext {
2078 DevelopmentToolContext {
2079 authorization: ToolAuthorization {
2080 actor: Actor::external("daemon-concurrency-test"),
2081 allow_mutation: true,
2082 confirmed: true,
2083 },
2084 initiator: None,
2085 expected_generation: 1,
2086 expected_project_revision: 0,
2087 }
2088 }
2089
2090 async fn wait_for_operation_state(
2091 operations: &Arc<Mutex<OperationRegistry>>,
2092 operation_id: &str,
2093 expected: DevelopmentOperationState,
2094 ) {
2095 let deadline = std::time::Instant::now() + Duration::from_secs(5);
2096 loop {
2097 let state = operations.lock().unwrap().records[operation_id].state;
2098 if state == expected {
2099 return;
2100 }
2101 assert!(
2102 std::time::Instant::now() < deadline,
2103 "operation {operation_id} remained {state:?}, expected {expected:?}"
2104 );
2105 tokio::time::sleep(Duration::from_millis(10)).await;
2106 }
2107 }
2108
2109 async fn submit_and_wait(
2110 socket: &Path,
2111 request_value: &DevelopmentDaemonRequest,
2112 ) -> DevelopmentDaemonResponse {
2113 let mut submission = request_value.clone();
2114 submission.operation = "operation.submit".into();
2115 let accepted = request(socket, &submission).await.unwrap();
2116 if !accepted.ok {
2117 return accepted;
2118 }
2119 let operation_id = accepted.result["operation"]["id"]
2120 .as_str()
2121 .unwrap()
2122 .to_string();
2123 for sequence in 0..2_000 {
2124 let mut inspect = submission.clone();
2125 inspect.id = format!("inspect-{}-{sequence}", submission.id);
2126 inspect.operation = "operation.inspect".into();
2127 inspect.call = None;
2128 inspect.expected_generation = None;
2129 inspect.expected_project_revision = None;
2130 inspect.allow_mutation = false;
2131 inspect.confirmed = false;
2132 inspect.operation_id = Some(operation_id.clone());
2133 let response = request(socket, &inspect).await.unwrap();
2134 if !response.ok {
2135 return response;
2136 }
2137 match response.result["operation"]["state"].as_str() {
2138 Some("succeeded") => {
2139 return DevelopmentDaemonResponse {
2140 id: submission.id,
2141 ok: true,
2142 result: response.result["operation"]["result"].clone(),
2143 error: None,
2144 };
2145 }
2146 Some("failed" | "cancelled" | "indeterminate") => {
2147 return DevelopmentDaemonResponse {
2148 id: submission.id,
2149 ok: false,
2150 result: Value::Null,
2151 error: response.result["operation"]["failureReason"]
2152 .as_str()
2153 .map(str::to_string)
2154 .or_else(|| Some("operation did not succeed".into())),
2155 };
2156 }
2157 _ => tokio::time::sleep(Duration::from_millis(10)).await,
2158 }
2159 }
2160 DevelopmentDaemonResponse {
2161 id: submission.id,
2162 ok: false,
2163 result: Value::Null,
2164 error: Some("operation did not settle in the test deadline".into()),
2165 }
2166 }
2167
2168 #[tokio::test(flavor = "current_thread")]
2169 async fn workspace_actors_do_not_serialize_unrelated_long_operations() {
2170 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2171 let base = std::env::temp_dir().join(format!(
2172 "glassd-actor-concurrency-{}-{sequence}",
2173 std::process::id()
2174 ));
2175 let first_root = base.join("first");
2176 let second_root = base.join("second");
2177 std::fs::create_dir_all(&first_root).unwrap();
2178 std::fs::create_dir_all(&second_root).unwrap();
2179 for root in [&first_root, &second_root] {
2180 std::fs::write(
2181 root.join("Cargo.toml"),
2182 "[package]\nname='stress-fixture'\nversion='0.1.0'\n",
2183 )
2184 .unwrap();
2185 }
2186 let dap_adapter = second_root.join("stress_dap.py");
2187 std::fs::write(
2188 &dap_adapter,
2189 r#"import json, sys
2190while True:
2191 line = sys.stdin.buffer.readline()
2192 if not line:
2193 break
2194 if not line.lower().startswith(b'content-length:'):
2195 continue
2196 length = int(line.split(b':', 1)[1])
2197 while sys.stdin.buffer.readline() not in (b'\r\n', b'\n', b''):
2198 pass
2199 request = json.loads(sys.stdin.buffer.read(length))
2200 response = {'seq': request['seq'] + 1000, 'type': 'response', 'request_seq': request['seq'], 'command': request['command'], 'success': True, 'body': {}}
2201 body = json.dumps(response).encode()
2202 sys.stdout.buffer.write(f'Content-Length: {len(body)}\r\n\r\n'.encode() + body)
2203 sys.stdout.buffer.flush()
2204"#,
2205 )
2206 .unwrap();
2207 let store = WorkspaceTrustStore::at(base.join("trust.json"));
2208 for root in [&first_root, &second_root] {
2209 store
2210 .trust_project(&crate::WorkspaceIdentity::inspect(root).unwrap())
2211 .unwrap();
2212 }
2213 let local = tokio::task::LocalSet::new();
2214 local
2215 .run_until(async {
2216 let actor = |id: &str, root: &Path| {
2217 let workspace =
2218 DevelopmentWorkspace::open_with_store(root, store.clone()).unwrap();
2219 let summary = workspace_summary(id, &workspace);
2220 let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2221 let operations = Arc::new(Mutex::new(OperationRegistry::new(id.into())));
2222 tokio::task::spawn_local(run_workspace_actor(
2223 id.into(),
2224 workspace,
2225 receiver,
2226 Arc::clone(&operations),
2227 ));
2228 WorkspaceActorHandle {
2229 sender,
2230 summary,
2231 operations,
2232 }
2233 };
2234 let first = actor("first", &first_root);
2235 let second = actor("second", &second_root);
2236 let python = ["python3", "python"]
2237 .into_iter()
2238 .find(|program| {
2239 std::process::Command::new(program)
2240 .arg("--version")
2241 .output()
2242 .is_ok_and(|output| output.status.success())
2243 })
2244 .expect("full-suite stress requires Python for the fixture DAP adapter");
2245 workspace_tool(
2246 second.clone(),
2247 ToolCall {
2248 id: "debug-start".into(),
2249 name: "glass.debug.start".into(),
2250 arguments: serde_json::json!({
2251 "session":"stress",
2252 "command":python,
2253 "arguments":[dap_adapter],
2254 "timeoutSeconds":3
2255 }),
2256 },
2257 test_context(),
2258 )
2259 .await
2260 .unwrap();
2261 let (kernel_kind, kernel_code) = if cfg!(windows) {
2262 ("python", "import time; time.sleep(3); print('complete')")
2263 } else {
2264 ("shell", "sleep 3; echo complete")
2265 };
2266 workspace_tool(
2267 first.clone(),
2268 ToolCall {
2269 id: "shell-start".into(),
2270 name: "glass.eval.start".into(),
2271 arguments: serde_json::json!({"name":"slow","kind":kernel_kind}),
2272 },
2273 test_context(),
2274 )
2275 .await
2276 .unwrap();
2277 let slow = tokio::task::spawn_local(workspace_tool(
2278 first.clone(),
2279 ToolCall {
2280 id: "shell-slow".into(),
2281 name: "glass.eval.execute".into(),
2282 arguments: serde_json::json!({
2283 "name":"slow",
2284 "code":kernel_code,
2285 "timeoutSeconds":5
2286 }),
2287 },
2288 test_context(),
2289 ));
2290 tokio::time::sleep(Duration::from_millis(50)).await;
2291 let (inspect, browser, lsp, debug, tests, processes) = tokio::join!(
2292 workspace_inspect(second.clone()),
2293 workspace_tool(
2294 second.clone(),
2295 ToolCall {
2296 id: "browser-state".into(),
2297 name: "glass.browser.state".into(),
2298 arguments: serde_json::json!({}),
2299 },
2300 test_context(),
2301 ),
2302 workspace_tool(
2303 second.clone(),
2304 ToolCall {
2305 id: "lsp-list".into(),
2306 name: "glass.lsp.list".into(),
2307 arguments: serde_json::json!({}),
2308 },
2309 test_context(),
2310 ),
2311 workspace_tool(
2312 second.clone(),
2313 ToolCall {
2314 id: "debug-events".into(),
2315 name: "glass.debug.events".into(),
2316 arguments: serde_json::json!({"session":"stress"}),
2317 },
2318 test_context(),
2319 ),
2320 workspace_tool(
2321 second.clone(),
2322 ToolCall {
2323 id: "test-discover".into(),
2324 name: "glass.test.discover".into(),
2325 arguments: serde_json::json!({}),
2326 },
2327 test_context(),
2328 ),
2329 workspace_tool(
2330 second.clone(),
2331 ToolCall {
2332 id: "process-list".into(),
2333 name: "glass.process.list".into(),
2334 arguments: serde_json::json!({}),
2335 },
2336 test_context(),
2337 ),
2338 );
2339 let inspect = inspect.unwrap();
2340 assert_eq!(inspect["workspace"]["id"], "second");
2341 assert!(browser.is_ok());
2342 assert!(lsp.is_ok());
2343 assert!(debug.is_ok());
2344 assert!(tests.is_ok());
2345 assert!(processes.is_ok());
2346 assert!(
2347 !slow.is_finished(),
2348 "unrelated workspace work waited for the slow operation"
2349 );
2350 assert!(slow.await.unwrap().is_ok());
2351 for handle in [first, second] {
2352 let (response, received) = tokio::sync::oneshot::channel();
2353 handle
2354 .sender
2355 .send(WorkspaceCommand::Shutdown { response })
2356 .await
2357 .unwrap();
2358 received.await.unwrap();
2359 }
2360 })
2361 .await;
2362 std::fs::remove_dir_all(base).unwrap();
2363 }
2364
2365 #[tokio::test(flavor = "current_thread")]
2366 async fn long_operations_reconnect_reconcile_and_cancel_by_stable_id() {
2367 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2368 let root = std::env::temp_dir().join(format!(
2369 "glassd-operation-lifecycle-{}-{sequence}",
2370 std::process::id()
2371 ));
2372 std::fs::create_dir_all(&root).unwrap();
2373 let store = WorkspaceTrustStore::at(root.join("trust.json"));
2374 store
2375 .trust_project(&crate::WorkspaceIdentity::inspect(&root).unwrap())
2376 .unwrap();
2377 let local = tokio::task::LocalSet::new();
2378 local
2379 .run_until(async {
2380 let workspace =
2381 DevelopmentWorkspace::open_with_store(&root, store.clone()).unwrap();
2382 let summary = workspace_summary("operations", &workspace);
2383 let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2384 let operations = Arc::new(Mutex::new(OperationRegistry::new("operations".into())));
2385 tokio::task::spawn_local(run_workspace_actor(
2386 "operations".into(),
2387 workspace,
2388 receiver,
2389 Arc::clone(&operations),
2390 ));
2391 let handle = WorkspaceActorHandle {
2392 sender: sender.clone(),
2393 summary: summary.clone(),
2394 operations: Arc::clone(&operations),
2395 };
2396 let (kernel_kind, slow_code) = if cfg!(windows) {
2397 ("python", "import time; time.sleep(0.2); print('complete')")
2398 } else {
2399 ("shell", "sleep 0.2; echo complete")
2400 };
2401 workspace_tool(
2402 handle.clone(),
2403 ToolCall {
2404 id: "operation-kernel-start".into(),
2405 name: "glass.eval.start".into(),
2406 arguments: serde_json::json!({"name":"operation","kind":kernel_kind}),
2407 },
2408 test_context(),
2409 )
2410 .await
2411 .unwrap();
2412
2413 let (first, created) = operations
2414 .lock()
2415 .unwrap()
2416 .submit(
2417 "stable-request",
2418 "test-client".into(),
2419 "glass.eval.execute".into(),
2420 0,
2421 true,
2422 )
2423 .unwrap();
2424 assert!(created);
2425 sender
2426 .send(WorkspaceCommand::SubmitOperation {
2427 operation_id: first.id.clone(),
2428 call: ToolCall {
2429 id: "operation-slow".into(),
2430 name: "glass.eval.execute".into(),
2431 arguments: serde_json::json!({
2432 "name":"operation",
2433 "code":slow_code,
2434 "timeoutSeconds":2
2435 }),
2436 },
2437 context: Box::new(test_context()),
2438 })
2439 .await
2440 .unwrap();
2441
2442 let reconnected = WorkspaceActorHandle {
2444 sender: sender.clone(),
2445 summary,
2446 operations: Arc::clone(&operations),
2447 };
2448 let immediate = reconnected.operations.lock().unwrap().records[&first.id].clone();
2449 assert!(matches!(
2450 immediate.state,
2451 DevelopmentOperationState::Queued | DevelopmentOperationState::Running
2452 ));
2453 let duplicate = operations
2454 .lock()
2455 .unwrap()
2456 .submit(
2457 "stable-request",
2458 "test-client".into(),
2459 "glass.eval.execute".into(),
2460 0,
2461 true,
2462 )
2463 .unwrap();
2464 assert!(!duplicate.1);
2465 assert_eq!(duplicate.0.id, first.id);
2466 wait_for_operation_state(
2467 &operations,
2468 &first.id,
2469 DevelopmentOperationState::Succeeded,
2470 )
2471 .await;
2472 let finished = operations.lock().unwrap().records[&first.id].clone();
2473 assert_eq!(finished.state, DevelopmentOperationState::Succeeded);
2474 assert!(finished.result.is_some());
2475 assert_eq!(finished.revision_after, Some(0));
2476
2477 let (cancelled, _) = operations
2478 .lock()
2479 .unwrap()
2480 .submit(
2481 "cancel-request",
2482 "test-client".into(),
2483 "glass.eval.execute".into(),
2484 0,
2485 true,
2486 )
2487 .unwrap();
2488 sender
2489 .send(WorkspaceCommand::SubmitOperation {
2490 operation_id: cancelled.id.clone(),
2491 call: ToolCall {
2492 id: "operation-cancel".into(),
2493 name: "glass.eval.execute".into(),
2494 arguments: serde_json::json!({
2495 "name":"operation",
2496 "code":if cfg!(windows) {
2497 "import time; time.sleep(2); print('cancel')"
2498 } else {
2499 "sleep 2; echo cancel"
2500 },
2501 "timeoutSeconds":5
2502 }),
2503 },
2504 context: Box::new(test_context()),
2505 })
2506 .await
2507 .unwrap();
2508 wait_for_operation_state(
2509 &operations,
2510 &cancelled.id,
2511 DevelopmentOperationState::Running,
2512 )
2513 .await;
2514 let cancelling = operations.lock().unwrap().cancel(&cancelled.id).unwrap();
2515 assert!(cancelling.cancellation_requested);
2516 wait_for_operation_state(
2517 &operations,
2518 &cancelled.id,
2519 DevelopmentOperationState::Cancelled,
2520 )
2521 .await;
2522 assert_eq!(
2523 operations.lock().unwrap().records[&cancelled.id].state,
2524 DevelopmentOperationState::Cancelled
2525 );
2526 assert!(
2527 operations
2528 .lock()
2529 .unwrap()
2530 .events
2531 .iter()
2532 .any(|event| event.operation_id == first.id
2533 && event.state == DevelopmentOperationState::Succeeded)
2534 );
2535
2536 let (response, received) = tokio::sync::oneshot::channel();
2537 reconnected
2538 .sender
2539 .send(WorkspaceCommand::Shutdown { response })
2540 .await
2541 .unwrap();
2542 received.await.unwrap();
2543 })
2544 .await;
2545 std::fs::remove_dir_all(root).unwrap();
2546 }
2547
2548 #[tokio::test(flavor = "current_thread")]
2549 async fn workspace_event_cursors_survive_client_reconnects() {
2550 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2551 let root = std::env::temp_dir().join(format!(
2552 "glassd-event-cursor-{}-{sequence}",
2553 std::process::id()
2554 ));
2555 std::fs::create_dir_all(&root).unwrap();
2556 let local = tokio::task::LocalSet::new();
2557 local
2558 .run_until(async {
2559 let workspace = DevelopmentWorkspace::open(&root).unwrap();
2560 let summary = workspace_summary("events", &workspace);
2561 let (sender, receiver) = tokio::sync::mpsc::channel(WORKSPACE_COMMAND_CAPACITY);
2562 let operations = Arc::new(Mutex::new(OperationRegistry::new("events".into())));
2563 tokio::task::spawn_local(run_workspace_actor(
2564 "events".into(),
2565 workspace,
2566 receiver,
2567 Arc::clone(&operations),
2568 ));
2569 let first_client = WorkspaceActorHandle {
2570 sender: sender.clone(),
2571 summary: summary.clone(),
2572 operations: Arc::clone(&operations),
2573 };
2574 workspace_tool(
2575 first_client,
2576 ToolCall {
2577 id: "task-list".into(),
2578 name: "glass.task.list".into(),
2579 arguments: serde_json::json!({}),
2580 },
2581 test_context(),
2582 )
2583 .await
2584 .unwrap();
2585 let first = workspace_events(
2586 WorkspaceActorHandle {
2587 sender: sender.clone(),
2588 summary: summary.clone(),
2589 operations: Arc::clone(&operations),
2590 },
2591 0,
2592 16,
2593 )
2594 .await
2595 .unwrap();
2596 assert_eq!(first["events"][0]["kind"], "workspace.opened");
2597 assert_eq!(first["events"][1]["kind"], "task.changed");
2598 let cursor = first["newestSequence"].as_u64().unwrap();
2599
2600 let reconnected = WorkspaceActorHandle {
2602 sender,
2603 summary,
2604 operations,
2605 };
2606 workspace_tool(
2607 reconnected.clone(),
2608 ToolCall {
2609 id: "task-list-after-reconnect".into(),
2610 name: "glass.task.list".into(),
2611 arguments: serde_json::json!({}),
2612 },
2613 test_context(),
2614 )
2615 .await
2616 .unwrap();
2617 let resumed = workspace_events(reconnected, cursor, 16).await.unwrap();
2618 assert_eq!(resumed["events"].as_array().unwrap().len(), 1);
2619 assert_eq!(resumed["events"][0]["kind"], "task.changed");
2620 assert_eq!(resumed["lostBefore"], Value::Null);
2621 })
2622 .await;
2623 std::fs::remove_dir_all(root).unwrap();
2624 }
2625
2626 #[test]
2627 fn workspace_event_overflow_is_bounded_and_observable() {
2628 let mut events = VecDeque::with_capacity(WORKSPACE_EVENT_CAPACITY);
2629 let mut next = 1;
2630 let mut dropped = 0;
2631 for index in 0..=WORKSPACE_EVENT_CAPACITY {
2632 push_workspace_event(
2633 "bounded",
2634 &mut events,
2635 &mut next,
2636 &mut dropped,
2637 "workspace.changed",
2638 Some(format!("call-{index}")),
2639 true,
2640 );
2641 }
2642 let batch = workspace_event_batch(&events, next, dropped, 0, MAX_EVENT_BATCH);
2643 assert_eq!(events.len(), WORKSPACE_EVENT_CAPACITY);
2644 assert_eq!(batch["droppedEvents"], 1);
2645 assert_eq!(batch["lostBefore"], 2);
2646 assert_eq!(batch["events"].as_array().unwrap().len(), MAX_EVENT_BATCH);
2647 }
2648
2649 #[tokio::test(flavor = "current_thread")]
2650 #[cfg(unix)]
2651 async fn daemon_preserves_resources_across_client_disconnects() {
2652 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2653 let base =
2654 std::env::temp_dir().join(format!("glassd-test-{}-{sequence}", std::process::id()));
2655 let project = base.join("project");
2656 std::fs::create_dir_all(&project).unwrap();
2657 std::fs::write(
2658 project.join("Cargo.toml"),
2659 "[package]\nname='x'\nversion='0.1.0'\n",
2660 )
2661 .unwrap();
2662 let trust_store = WorkspaceTrustStore::at(base.join("trust.json"));
2663 trust_store
2664 .trust_project(&crate::WorkspaceIdentity::inspect(&project).unwrap())
2665 .unwrap();
2666 let socket = base.join("glassd.sock");
2667 let status = base.join("glassd.json");
2668 let local = tokio::task::LocalSet::new();
2669 local
2670 .run_until(async {
2671 let server_socket = socket.clone();
2672 let server_status = status.clone();
2673 let server_trust_store = trust_store.clone();
2674 let server = tokio::task::spawn_local(async move {
2675 serve_with_store(&server_socket, &server_status, server_trust_store)
2676 .await
2677 .unwrap()
2678 });
2679 for _ in 0..100 {
2680 if status.exists() && socket.exists() {
2681 break;
2682 }
2683 tokio::time::sleep(Duration::from_millis(10)).await;
2684 }
2685 let token = std::fs::read_to_string(token_path(&status)).unwrap();
2686 let base_request = |id: &str, operation: &str| DevelopmentDaemonRequest {
2687 id: id.into(),
2688 token: token.clone(),
2689 operation: operation.into(),
2690 workspace_id: Some("fixture".into()),
2691 root: None,
2692 call: None,
2693 expected_generation: None,
2694 expected_project_revision: None,
2695 allow_mutation: false,
2696 confirmed: false,
2697 actor: Some("test-client".into()),
2698 since: None,
2699 limit: None,
2700 operation_id: None,
2701 };
2702 let mut open = base_request("open", "workspace.open");
2703 open.root = Some(project.clone());
2704 assert!(request(&socket, &open).await.unwrap().ok);
2705 let mut start = base_request("start", "operation.submit");
2706 start.call = Some(ToolCall {
2707 id: "kernel-start".into(),
2708 name: "glass.eval.start".into(),
2709 arguments: serde_json::json!({"name":"durable","kind":"sql"}),
2710 });
2711 start.expected_generation = Some(1);
2712 start.expected_project_revision = Some(0);
2713 start.allow_mutation = true;
2714 start.confirmed = true;
2715 assert!(submit_and_wait(&socket, &start).await.ok);
2716 let mut process_start = base_request("process-start", "operation.submit");
2717 process_start.call = Some(ToolCall {
2718 id: "process-start".into(),
2719 name: "glass.process.start".into(),
2720 arguments: serde_json::json!({"name":"durable-process","command":"sleep 30"}),
2721 });
2722 process_start.expected_generation = Some(1);
2723 process_start.expected_project_revision = Some(0);
2724 process_start.allow_mutation = true;
2725 process_start.confirmed = true;
2726 assert!(submit_and_wait(&socket, &process_start).await.ok);
2727 let pi_available = std::process::Command::new("pi")
2728 .arg("--version")
2729 .output()
2730 .is_ok();
2731 if pi_available {
2732 let mut agent_start = base_request("agent-start", "operation.submit");
2733 agent_start.call = Some(ToolCall {
2734 id: "agent-start".into(),
2735 name: "glass.agent.spawn".into(),
2736 arguments: serde_json::json!({"spec":{
2737 "role":"durability-probe",
2738 "task":"Remain idle while the client reconnects",
2739 "dependencies":[],
2740 "model":null,
2741 "thinking":null,
2742 "worktree":null,
2743 "unrestricted":false,
2744 "maxRuntimeSeconds":60,
2745 "maxEvents":100
2746 }}),
2747 });
2748 agent_start.expected_generation = Some(1);
2749 agent_start.expected_project_revision = Some(1);
2750 agent_start.allow_mutation = true;
2751 agent_start.confirmed = true;
2752 let agent_response = submit_and_wait(&socket, &agent_start).await;
2753 assert!(agent_response.ok, "{:?}", agent_response.error);
2754 }
2755 let browser_e2e = std::env::var("GLASS_E2E").as_deref() == Ok("1")
2756 && std::env::var_os("GLASS_CHROME_PATH").is_some();
2757 if browser_e2e {
2758 let port_probe = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
2759 let browser_port = port_probe.local_addr().unwrap().port();
2760 drop(port_probe);
2761 let mut browser_start = base_request("browser-start", "operation.submit");
2762 browser_start.call = Some(ToolCall {
2763 id: "browser-start".into(),
2764 name: "glass.browser.start".into(),
2765 arguments: serde_json::json!({
2766 "port":browser_port,
2767 "incognito":true,
2768 "chromePath":std::env::var("GLASS_CHROME_PATH").unwrap()
2769 }),
2770 });
2771 browser_start.expected_generation = Some(1);
2772 browser_start.expected_project_revision = Some(1);
2773 browser_start.allow_mutation = true;
2774 browser_start.confirmed = true;
2775 let response = submit_and_wait(&socket, &browser_start).await;
2776 assert!(response.ok, "{:?}", response.error);
2777 }
2778 let call = ToolCall {
2781 id: "kernel-execute".into(),
2782 name: "glass.eval.execute".into(),
2783 arguments: serde_json::json!({"name":"durable","code":"SELECT 42 AS answer"}),
2784 };
2785 let call_path = std::env::temp_dir().join(format!(
2786 "glass-pi-call-{}-{sequence}.json",
2787 std::process::id()
2788 ));
2789 write_private(&call_path, &serde_json::to_vec(&call).unwrap()).unwrap();
2790 let result = forward_resident_tool_file_with_context(
2791 &socket, &token, "fixture", &call_path, &project, true, true,
2792 )
2793 .await
2794 .unwrap();
2795 assert_eq!(result["value"][0]["answer"], 42);
2796 let inspect = request(
2799 &socket,
2800 &base_request("inspect-reconnected", "workspace.inspect"),
2801 )
2802 .await
2803 .unwrap();
2804 assert!(inspect.ok);
2805 assert!(
2806 inspect.result["processes"]
2807 .as_array()
2808 .unwrap()
2809 .iter()
2810 .any(|process| process["name"] == "durable-process")
2811 );
2812 assert!(
2813 inspect.result["kernels"]
2814 .as_array()
2815 .unwrap()
2816 .iter()
2817 .any(|kernel| kernel["name"] == "durable")
2818 );
2819 if pi_available {
2820 assert!(!inspect.result["agents"].as_array().unwrap().is_empty());
2821 }
2822 assert_eq!(inspect.result["browser"]["connected"], browser_e2e);
2823 let mut process_stop = base_request("process-stop", "operation.submit");
2824 process_stop.call = Some(ToolCall {
2825 id: "process-stop".into(),
2826 name: "glass.process.stop".into(),
2827 arguments: serde_json::json!({"name":"durable-process"}),
2828 });
2829 process_stop.expected_generation = Some(1);
2830 process_stop.expected_project_revision = Some(1);
2831 process_stop.allow_mutation = true;
2832 process_stop.confirmed = true;
2833 assert!(submit_and_wait(&socket, &process_stop).await.ok);
2834 if browser_e2e {
2835 let mut browser_stop = base_request("browser-stop", "operation.submit");
2836 browser_stop.call = Some(ToolCall {
2837 id: "browser-stop".into(),
2838 name: "glass.browser.stop".into(),
2839 arguments: serde_json::json!({}),
2840 });
2841 browser_stop.expected_generation = Some(1);
2842 browser_stop.expected_project_revision = Some(2);
2843 browser_stop.allow_mutation = true;
2844 browser_stop.confirmed = true;
2845 assert!(submit_and_wait(&socket, &browser_stop).await.ok);
2846 }
2847 server.abort();
2848 })
2849 .await;
2850 let _ = std::fs::remove_dir_all(base);
2851 }
2852
2853 #[tokio::test(flavor = "current_thread")]
2854 #[cfg(unix)]
2855 async fn daemon_reconnect_preserves_untrusted_state_and_cannot_elevate_it() {
2856 let sequence = NEXT_ROOT.fetch_add(1, Ordering::Relaxed);
2857 let base = std::env::temp_dir().join(format!(
2858 "glassd-trust-test-{}-{sequence}",
2859 std::process::id()
2860 ));
2861 let project = base.join("project");
2862 std::fs::create_dir_all(&project).unwrap();
2863 std::fs::write(
2864 project.join("glass.toml"),
2865 "[tools.hostile]\ndescription='hostile'\ncommand='echo unsafe'\n",
2866 )
2867 .unwrap();
2868 let socket = base.join("glassd.sock");
2869 let status = base.join("glassd.json");
2870 let local = tokio::task::LocalSet::new();
2871 local
2872 .run_until(async {
2873 let server_socket = socket.clone();
2874 let server_status = status.clone();
2875 let store = WorkspaceTrustStore::at(base.join("trust.json"));
2876 let server = tokio::task::spawn_local(async move {
2877 serve_with_store(&server_socket, &server_status, store)
2878 .await
2879 .unwrap()
2880 });
2881 for _ in 0..100 {
2882 if status.exists() && socket.exists() {
2883 break;
2884 }
2885 tokio::time::sleep(Duration::from_millis(10)).await;
2886 }
2887 let token = std::fs::read_to_string(token_path(&status)).unwrap();
2888 let base_request = |id: &str, operation: &str| DevelopmentDaemonRequest {
2889 id: id.into(),
2890 token: token.clone(),
2891 operation: operation.into(),
2892 workspace_id: Some("untrusted".into()),
2893 root: None,
2894 call: None,
2895 expected_generation: None,
2896 expected_project_revision: None,
2897 allow_mutation: false,
2898 confirmed: false,
2899 actor: Some("external-agent".into()),
2900 since: None,
2901 limit: None,
2902 operation_id: None,
2903 };
2904 let mut open = base_request("open", "workspace.open");
2905 open.root = Some(project.clone());
2906 let opened = request(&socket, &open).await.unwrap();
2907 assert!(opened.ok);
2908 assert_eq!(opened.result["trust"], "untrusted");
2909
2910 let inspected = request(&socket, &base_request("inspect", "workspace.inspect"))
2913 .await
2914 .unwrap();
2915 assert!(inspected.ok);
2916 assert_eq!(inspected.result["workspace"]["trust"], "untrusted");
2917
2918 let mut tool = base_request("tool", "operation.submit");
2919 tool.call = Some(ToolCall {
2920 id: "hostile".into(),
2921 name: "glass.custom.hostile".into(),
2922 arguments: serde_json::json!({}),
2923 });
2924 tool.expected_generation = Some(1);
2925 tool.expected_project_revision = Some(0);
2926 tool.allow_mutation = true;
2927 tool.confirmed = true;
2928 let denied = submit_and_wait(&socket, &tool).await;
2929 assert!(!denied.ok);
2930 assert!(denied.error.unwrap().contains("trust"));
2931 server.abort();
2932 })
2933 .await;
2934 let _ = std::fs::remove_dir_all(base);
2935 }
2936
2937 #[test]
2938 fn daemon_identifiers_and_status_quotas_fail_closed() {
2939 assert!(validate_identifier("workspace-1", "workspace").is_ok());
2940 assert!(validate_identifier("../escape", "workspace").is_err());
2941 }
2942}