Skip to main content

glass_dev/
daemon.rs

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