Skip to main content

glass_dev/
debugger.rs

1//! Resident Debug Adapter Protocol runtime.
2//!
3//! The runtime owns one adapter process and speaks bounded DAP framing over
4//! stdio. Higher-level debugger methods retain adapter-neutral JSON bodies so
5//! LLDB, debugpy, Delve and JavaScript adapters can share one implementation.
6
7use serde::{Deserialize, Serialize};
8use serde_json::{Value, json};
9use std::collections::VecDeque;
10use std::fmt;
11use std::io::{BufRead, BufReader, Write};
12use std::path::{Path, PathBuf};
13use std::process::{Child, ChildStdin, Command, Stdio};
14use std::sync::mpsc::{self, Receiver, RecvTimeoutError, TrySendError};
15use std::thread::JoinHandle;
16use std::time::{Duration, Instant};
17
18const MAX_DAP_HEADER_BYTES: usize = 8 * 1024;
19const MAX_DAP_MESSAGE_BYTES: usize = 4 * 1024 * 1024;
20const MAX_PENDING_MESSAGES: usize = 512;
21
22pub type DebugResult<T> = Result<T, DebugError>;
23
24#[derive(Debug)]
25pub enum DebugError {
26    Io(std::io::Error),
27    InvalidInput(String),
28    Protocol(String),
29    Adapter(String),
30    Timeout(String),
31}
32
33impl fmt::Display for DebugError {
34    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
35        match self {
36            Self::Io(error) => write!(formatter, "debug adapter I/O error: {error}"),
37            Self::InvalidInput(message) => write!(formatter, "invalid debugger input: {message}"),
38            Self::Protocol(message) => write!(formatter, "debug adapter protocol error: {message}"),
39            Self::Adapter(message) => {
40                write!(formatter, "debug adapter rejected request: {message}")
41            }
42            Self::Timeout(message) => write!(formatter, "debug adapter timeout: {message}"),
43        }
44    }
45}
46
47impl std::error::Error for DebugError {}
48
49impl From<std::io::Error> for DebugError {
50    fn from(error: std::io::Error) -> Self {
51        Self::Io(error)
52    }
53}
54
55#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
56pub struct DebugAdapterConfig {
57    pub command: PathBuf,
58    #[serde(default)]
59    pub arguments: Vec<String>,
60}
61
62impl DebugAdapterConfig {
63    pub fn new(command: impl Into<PathBuf>, arguments: impl IntoIterator<Item = String>) -> Self {
64        Self {
65            command: command.into(),
66            arguments: arguments.into_iter().collect(),
67        }
68    }
69}
70
71#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
72#[serde(rename_all = "camelCase")]
73pub enum DebugSessionState {
74    Starting,
75    Initialized,
76    Running,
77    Stopped,
78    Terminated,
79    Failed,
80}
81
82#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
83pub struct DebugEvent {
84    pub event: String,
85    #[serde(default)]
86    pub body: Value,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
90#[serde(rename_all = "camelCase")]
91pub struct SourceBreakpoint {
92    pub line: u64,
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub condition: Option<String>,
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub hit_condition: Option<String>,
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub log_message: Option<String>,
99}
100
101impl SourceBreakpoint {
102    pub fn line(line: u64) -> Self {
103        Self {
104            line,
105            condition: None,
106            hit_condition: None,
107            log_message: None,
108        }
109    }
110}
111
112/// One owned DAP adapter process with bounded request and event queues.
113pub struct DapClient {
114    child: Child,
115    stdin: ChildStdin,
116    messages: Receiver<DebugResult<Value>>,
117    reader: Option<JoinHandle<()>>,
118    stderr_drain: Option<JoinHandle<()>>,
119    pending: VecDeque<Value>,
120    next_sequence: u64,
121}
122
123impl DapClient {
124    pub fn spawn(root: &Path, config: &DebugAdapterConfig) -> DebugResult<Self> {
125        if !root.is_dir() {
126            return Err(DebugError::InvalidInput(format!(
127                "debugger project root is not a directory: {}",
128                root.display()
129            )));
130        }
131        if config.command.as_os_str().is_empty() {
132            return Err(DebugError::InvalidInput(
133                "debug adapter command must not be empty".into(),
134            ));
135        }
136        let mut child = Command::new(&config.command)
137            .args(&config.arguments)
138            .current_dir(root)
139            .stdin(Stdio::piped())
140            .stdout(Stdio::piped())
141            .stderr(Stdio::piped())
142            .spawn()?;
143        let stdin = child
144            .stdin
145            .take()
146            .ok_or_else(|| DebugError::Protocol("adapter stdin was unavailable".into()))?;
147        let stdout = child
148            .stdout
149            .take()
150            .ok_or_else(|| DebugError::Protocol("adapter stdout was unavailable".into()))?;
151        let stderr = child
152            .stderr
153            .take()
154            .ok_or_else(|| DebugError::Protocol("adapter stderr was unavailable".into()))?;
155        let (sender, messages) = mpsc::sync_channel(MAX_PENDING_MESSAGES);
156        let reader = std::thread::spawn(move || {
157            let mut stdout = BufReader::new(stdout);
158            loop {
159                match read_dap_message(&mut stdout) {
160                    Ok(Some(message)) => match sender.try_send(Ok(message)) {
161                        Ok(()) => {}
162                        Err(TrySendError::Full(_) | TrySendError::Disconnected(_)) => break,
163                    },
164                    Ok(None) => break,
165                    Err(error) => {
166                        let _ = sender.try_send(Err(error));
167                        break;
168                    }
169                }
170            }
171        });
172        let stderr_drain = std::thread::spawn(move || {
173            let mut stderr = stderr;
174            let mut sink = std::io::sink();
175            let _ = std::io::copy(&mut stderr, &mut sink);
176        });
177        Ok(Self {
178            child,
179            stdin,
180            messages,
181            reader: Some(reader),
182            stderr_drain: Some(stderr_drain),
183            pending: VecDeque::new(),
184            next_sequence: 1,
185        })
186    }
187
188    pub fn process_id(&self) -> u32 {
189        self.child.id()
190    }
191
192    pub fn request(
193        &mut self,
194        command: &str,
195        arguments: Value,
196        timeout: Duration,
197    ) -> DebugResult<Value> {
198        let sequence = self.send_request(command, arguments)?;
199        self.wait_for_response(sequence, command, timeout)
200    }
201
202    fn send_request(&mut self, command: &str, arguments: Value) -> DebugResult<u64> {
203        if command.is_empty() || command.len() > 128 {
204            return Err(DebugError::InvalidInput(
205                "DAP command must contain 1..=128 bytes".into(),
206            ));
207        }
208        let sequence = self.next_sequence;
209        self.next_sequence = self
210            .next_sequence
211            .checked_add(1)
212            .ok_or_else(|| DebugError::Protocol("DAP sequence overflowed".into()))?;
213        write_dap_message(
214            &mut self.stdin,
215            &json!({
216                "seq": sequence,
217                "type": "request",
218                "command": command,
219                "arguments": arguments,
220            }),
221        )?;
222
223        Ok(sequence)
224    }
225
226    fn wait_for_response(
227        &mut self,
228        sequence: u64,
229        command: &str,
230        timeout: Duration,
231    ) -> DebugResult<Value> {
232        let deadline = Instant::now() + timeout;
233        loop {
234            if let Some(response) = take_response(&mut self.pending, sequence) {
235                return response_body(response, command);
236            }
237            let remaining = deadline.saturating_duration_since(Instant::now());
238            if remaining.is_zero() {
239                return Err(DebugError::Timeout(format!(
240                    "request {command} exceeded {} ms",
241                    timeout.as_millis()
242                )));
243            }
244            match self.messages.recv_timeout(remaining) {
245                Ok(Ok(message)) => {
246                    if is_response_for(&message, sequence) {
247                        return response_body(message, command);
248                    }
249                    push_pending(&mut self.pending, message)?;
250                }
251                Ok(Err(error)) => return Err(error),
252                Err(RecvTimeoutError::Timeout) => {
253                    return Err(DebugError::Timeout(format!(
254                        "request {command} exceeded {} ms",
255                        timeout.as_millis()
256                    )));
257                }
258                Err(RecvTimeoutError::Disconnected) => {
259                    return Err(DebugError::Protocol(
260                        "debug adapter event stream closed".into(),
261                    ));
262                }
263            }
264        }
265    }
266
267    pub fn poll_events(&mut self) -> DebugResult<Vec<DebugEvent>> {
268        while let Ok(message) = self.messages.try_recv() {
269            push_pending(&mut self.pending, message?)?;
270        }
271        let mut events = Vec::new();
272        let mut retained = VecDeque::new();
273        while let Some(message) = self.pending.pop_front() {
274            if message.get("type").and_then(Value::as_str) == Some("event") {
275                let event = message
276                    .get("event")
277                    .and_then(Value::as_str)
278                    .ok_or_else(|| DebugError::Protocol("DAP event has no name".into()))?;
279                events.push(DebugEvent {
280                    event: event.to_string(),
281                    body: message.get("body").cloned().unwrap_or(Value::Null),
282                });
283            } else {
284                retained.push_back(message);
285            }
286        }
287        self.pending = retained;
288        Ok(events)
289    }
290
291    pub fn shutdown(&mut self) -> DebugResult<()> {
292        if self.child.try_wait()?.is_none() {
293            let _ = self.request(
294                "disconnect",
295                json!({"terminateDebuggee": true}),
296                Duration::from_secs(2),
297            );
298            if self.child.try_wait()?.is_none() {
299                self.child.kill()?;
300            }
301            let _ = self.child.wait();
302        }
303        if let Some(reader) = self.reader.take() {
304            let _ = reader.join();
305        }
306        if let Some(stderr_drain) = self.stderr_drain.take() {
307            let _ = stderr_drain.join();
308        }
309        Ok(())
310    }
311}
312
313impl Drop for DapClient {
314    fn drop(&mut self) {
315        if self.child.try_wait().ok().flatten().is_none() {
316            let _ = self.child.kill();
317            let _ = self.child.wait();
318        }
319        if let Some(reader) = self.reader.take() {
320            let _ = reader.join();
321        }
322        if let Some(stderr_drain) = self.stderr_drain.take() {
323            let _ = stderr_drain.join();
324        }
325    }
326}
327
328/// Adapter-neutral debugger session state and typed operations.
329pub struct DebuggerSession {
330    client: DapClient,
331    state: DebugSessionState,
332    capabilities: Value,
333    timeout: Duration,
334    pending_start: Option<(u64, &'static str)>,
335}
336
337impl DebuggerSession {
338    pub fn start(
339        root: &Path,
340        config: &DebugAdapterConfig,
341        client_name: &str,
342        timeout: Duration,
343    ) -> DebugResult<Self> {
344        let mut client = DapClient::spawn(root, config)?;
345        let capabilities = client.request(
346            "initialize",
347            json!({
348                "clientID": "glass-dev",
349                "clientName": client_name,
350                "adapterID": "glass",
351                "pathFormat": "path",
352                "linesStartAt1": true,
353                "columnsStartAt1": true,
354                "supportsVariableType": true,
355                "supportsVariablePaging": true,
356                "supportsRunInTerminalRequest": false,
357            }),
358            timeout,
359        )?;
360        Ok(Self {
361            client,
362            state: DebugSessionState::Initialized,
363            capabilities,
364            timeout,
365            pending_start: None,
366        })
367    }
368
369    pub fn state(&self) -> DebugSessionState {
370        self.state
371    }
372
373    pub fn capabilities(&self) -> &Value {
374        &self.capabilities
375    }
376
377    pub fn launch(&mut self, arguments: Value) -> DebugResult<Value> {
378        self.begin_start("launch", arguments)
379    }
380
381    pub fn attach(&mut self, arguments: Value) -> DebugResult<Value> {
382        self.begin_start("attach", arguments)
383    }
384
385    pub fn configuration_done(&mut self) -> DebugResult<Value> {
386        let configuration = self
387            .client
388            .request("configurationDone", json!({}), self.timeout)?;
389        let startup = if let Some((sequence, command)) = self.pending_start.take() {
390            self.client
391                .wait_for_response(sequence, command, self.timeout)?
392        } else {
393            Value::Null
394        };
395        self.state = DebugSessionState::Running;
396        Ok(json!({"configurationDone": configuration, "startup": startup}))
397    }
398
399    fn begin_start(&mut self, command: &'static str, arguments: Value) -> DebugResult<Value> {
400        if self.pending_start.is_some() {
401            return Err(DebugError::InvalidInput(
402                "a debugger launch or attach request is already pending".into(),
403            ));
404        }
405        let sequence = self.client.send_request(command, arguments)?;
406        self.pending_start = Some((sequence, command));
407        self.state = DebugSessionState::Starting;
408        Ok(json!({"pending": true, "requestSequence": sequence}))
409    }
410
411    pub fn restart(&mut self, arguments: Value) -> DebugResult<Value> {
412        let body = self.client.request("restart", arguments, self.timeout)?;
413        self.state = DebugSessionState::Running;
414        Ok(body)
415    }
416
417    pub fn set_breakpoints(&mut self, path: &Path, lines: &[u64]) -> DebugResult<Value> {
418        let breakpoints = lines
419            .iter()
420            .copied()
421            .map(SourceBreakpoint::line)
422            .collect::<Vec<_>>();
423        self.set_source_breakpoints(path, &breakpoints)
424    }
425
426    pub fn set_source_breakpoints(
427        &mut self,
428        path: &Path,
429        breakpoints: &[SourceBreakpoint],
430    ) -> DebugResult<Value> {
431        if breakpoints.len() > 256 || breakpoints.iter().any(|item| item.line == 0) {
432            return Err(DebugError::InvalidInput(
433                "breakpoints require at most 256 positive line numbers".into(),
434            ));
435        }
436        self.client.request(
437            "setBreakpoints",
438            json!({
439                "source": {"path": path},
440                "breakpoints": breakpoints,
441                "sourceModified": false,
442            }),
443            self.timeout,
444        )
445    }
446
447    pub fn set_exception_breakpoints(&mut self, filters: &[String]) -> DebugResult<Value> {
448        self.client.request(
449            "setExceptionBreakpoints",
450            json!({"filters": filters}),
451            self.timeout,
452        )
453    }
454
455    pub fn continue_thread(&mut self, thread_id: i64) -> DebugResult<Value> {
456        let body = self.client.request(
457            "continue",
458            json!({"threadId": positive_id(thread_id, "thread")?}),
459            self.timeout,
460        )?;
461        self.state = DebugSessionState::Running;
462        Ok(body)
463    }
464
465    pub fn pause(&mut self, thread_id: i64) -> DebugResult<Value> {
466        self.client.request(
467            "pause",
468            json!({"threadId": positive_id(thread_id, "thread")?}),
469            self.timeout,
470        )
471    }
472
473    pub fn next(&mut self, thread_id: i64) -> DebugResult<Value> {
474        self.step("next", thread_id)
475    }
476
477    pub fn step_in(&mut self, thread_id: i64) -> DebugResult<Value> {
478        self.step("stepIn", thread_id)
479    }
480
481    pub fn step_out(&mut self, thread_id: i64) -> DebugResult<Value> {
482        self.step("stepOut", thread_id)
483    }
484
485    fn step(&mut self, command: &str, thread_id: i64) -> DebugResult<Value> {
486        let body = self.client.request(
487            command,
488            json!({"threadId": positive_id(thread_id, "thread")?}),
489            self.timeout,
490        )?;
491        self.state = DebugSessionState::Running;
492        Ok(body)
493    }
494
495    pub fn threads(&mut self) -> DebugResult<Value> {
496        self.client.request("threads", json!({}), self.timeout)
497    }
498
499    pub fn stack_trace(&mut self, thread_id: i64) -> DebugResult<Value> {
500        self.client.request(
501            "stackTrace",
502            json!({"threadId": positive_id(thread_id, "thread")?}),
503            self.timeout,
504        )
505    }
506
507    pub fn scopes(&mut self, frame_id: i64) -> DebugResult<Value> {
508        self.client.request(
509            "scopes",
510            json!({"frameId": positive_id(frame_id, "frame")?}),
511            self.timeout,
512        )
513    }
514
515    pub fn variables(&mut self, variables_reference: i64) -> DebugResult<Value> {
516        self.client.request(
517            "variables",
518            json!({"variablesReference": positive_id(variables_reference, "variables reference")?}),
519            self.timeout,
520        )
521    }
522
523    pub fn evaluate(
524        &mut self,
525        expression: &str,
526        frame_id: Option<i64>,
527        context: &str,
528    ) -> DebugResult<Value> {
529        if expression.is_empty() || expression.len() > 64 * 1024 {
530            return Err(DebugError::InvalidInput(
531                "debug evaluation expression must contain 1..=65536 bytes".into(),
532            ));
533        }
534        let mut arguments = json!({"expression": expression, "context": context});
535        if let Some(frame_id) = frame_id {
536            arguments["frameId"] = json!(positive_id(frame_id, "frame")?);
537        }
538        self.client.request("evaluate", arguments, self.timeout)
539    }
540
541    pub fn poll_events(&mut self) -> DebugResult<Vec<DebugEvent>> {
542        let events = self.client.poll_events()?;
543        for event in &events {
544            match event.event.as_str() {
545                "stopped" => self.state = DebugSessionState::Stopped,
546                "continued" => self.state = DebugSessionState::Running,
547                "terminated" | "exited" => self.state = DebugSessionState::Terminated,
548                _ => {}
549            }
550        }
551        Ok(events)
552    }
553
554    pub fn disconnect(&mut self, terminate_debuggee: bool) -> DebugResult<Value> {
555        let result = self.client.request(
556            "disconnect",
557            json!({"terminateDebuggee": terminate_debuggee}),
558            self.timeout,
559        );
560        self.state = DebugSessionState::Terminated;
561        result
562    }
563
564    pub fn terminate(&mut self, restart: bool) -> DebugResult<Value> {
565        let result = self
566            .client
567            .request("terminate", json!({"restart": restart}), self.timeout);
568        self.state = if restart {
569            DebugSessionState::Starting
570        } else {
571            DebugSessionState::Terminated
572        };
573        result
574    }
575
576    pub fn shutdown(&mut self) -> DebugResult<()> {
577        self.state = DebugSessionState::Terminated;
578        self.client.shutdown()
579    }
580}
581
582fn positive_id(value: i64, description: &str) -> DebugResult<i64> {
583    (value > 0).then_some(value).ok_or_else(|| {
584        DebugError::InvalidInput(format!("{description} ID must be a positive integer"))
585    })
586}
587
588fn push_pending(pending: &mut VecDeque<Value>, message: Value) -> DebugResult<()> {
589    if pending.len() == MAX_PENDING_MESSAGES {
590        return Err(DebugError::Protocol(format!(
591            "debug adapter exceeded the {MAX_PENDING_MESSAGES} pending message limit"
592        )));
593    }
594    pending.push_back(message);
595    Ok(())
596}
597
598fn take_response(pending: &mut VecDeque<Value>, sequence: u64) -> Option<Value> {
599    let position = pending
600        .iter()
601        .position(|message| is_response_for(message, sequence))?;
602    pending.remove(position)
603}
604
605fn is_response_for(message: &Value, sequence: u64) -> bool {
606    message.get("type").and_then(Value::as_str) == Some("response")
607        && message.get("request_seq").and_then(Value::as_u64) == Some(sequence)
608}
609
610fn response_body(message: Value, command: &str) -> DebugResult<Value> {
611    if message.get("success").and_then(Value::as_bool) != Some(true) {
612        let detail = message
613            .get("message")
614            .and_then(Value::as_str)
615            .unwrap_or("adapter returned an unsuccessful response");
616        return Err(DebugError::Adapter(format!("{command}: {detail}")));
617    }
618    Ok(message.get("body").cloned().unwrap_or(Value::Null))
619}
620
621fn read_dap_message(reader: &mut impl BufRead) -> DebugResult<Option<Value>> {
622    let mut content_length = None;
623    let mut header_bytes = 0usize;
624    loop {
625        let mut line = String::new();
626        let read = reader.read_line(&mut line)?;
627        if read == 0 {
628            return if header_bytes == 0 {
629                Ok(None)
630            } else {
631                Err(DebugError::Protocol("truncated DAP header".into()))
632            };
633        }
634        header_bytes = header_bytes
635            .checked_add(read)
636            .ok_or_else(|| DebugError::Protocol("DAP header length overflowed".into()))?;
637        if header_bytes > MAX_DAP_HEADER_BYTES {
638            return Err(DebugError::Protocol(format!(
639                "DAP header exceeds {MAX_DAP_HEADER_BYTES} bytes"
640            )));
641        }
642        if line == "\r\n" || line == "\n" {
643            break;
644        }
645        if let Some((name, value)) = line.trim().split_once(':')
646            && name.eq_ignore_ascii_case("Content-Length")
647        {
648            content_length =
649                Some(value.trim().parse::<usize>().map_err(|_| {
650                    DebugError::Protocol("invalid DAP Content-Length header".into())
651                })?);
652        }
653    }
654    let content_length = content_length
655        .ok_or_else(|| DebugError::Protocol("DAP message has no Content-Length header".into()))?;
656    if content_length == 0 || content_length > MAX_DAP_MESSAGE_BYTES {
657        return Err(DebugError::Protocol(format!(
658            "DAP message length must be 1..={MAX_DAP_MESSAGE_BYTES} bytes"
659        )));
660    }
661    let mut body = vec![0; content_length];
662    reader.read_exact(&mut body)?;
663    serde_json::from_slice(&body)
664        .map_err(|error| DebugError::Protocol(format!("invalid DAP JSON: {error}")))
665}
666
667fn write_dap_message(writer: &mut impl Write, message: &Value) -> DebugResult<()> {
668    let body = serde_json::to_vec(message)
669        .map_err(|error| DebugError::Protocol(format!("could not encode DAP JSON: {error}")))?;
670    if body.is_empty() || body.len() > MAX_DAP_MESSAGE_BYTES {
671        return Err(DebugError::Protocol(format!(
672            "DAP message length must be 1..={MAX_DAP_MESSAGE_BYTES} bytes"
673        )));
674    }
675    write!(writer, "Content-Length: {}\r\n\r\n", body.len())?;
676    writer.write_all(&body)?;
677    writer.flush()?;
678    Ok(())
679}
680
681#[cfg(test)]
682mod tests {
683    use super::*;
684    use std::io::Cursor;
685
686    #[test]
687    fn dap_framing_round_trips_json() {
688        let message = json!({"seq": 7, "type": "event", "event": "stopped"});
689        let mut encoded = Vec::new();
690        write_dap_message(&mut encoded, &message).unwrap();
691        assert_eq!(
692            read_dap_message(&mut BufReader::new(Cursor::new(encoded))).unwrap(),
693            Some(message)
694        );
695    }
696
697    #[test]
698    fn dap_framing_rejects_missing_and_oversized_lengths() {
699        let missing = b"X-Test: true\r\n\r\n{}";
700        assert!(read_dap_message(&mut BufReader::new(&missing[..])).is_err());
701        let oversized = format!("Content-Length: {}\r\n\r\n", MAX_DAP_MESSAGE_BYTES + 1);
702        assert!(read_dap_message(&mut BufReader::new(oversized.as_bytes())).is_err());
703    }
704
705    #[test]
706    fn unsuccessful_adapter_response_is_typed() {
707        let error = response_body(
708            json!({
709                "type": "response",
710                "request_seq": 1,
711                "success": false,
712                "message": "breakpoint refused"
713            }),
714            "setBreakpoints",
715        )
716        .unwrap_err();
717        assert!(error.to_string().contains("breakpoint refused"));
718    }
719
720    #[test]
721    fn debugger_ids_and_breakpoint_limits_fail_closed() {
722        assert!(positive_id(0, "thread").is_err());
723        assert!(positive_id(-1, "frame").is_err());
724        assert_eq!(positive_id(1, "thread").unwrap(), 1);
725
726        let breakpoint = SourceBreakpoint {
727            line: 42,
728            condition: Some("inventory == 0".into()),
729            hit_condition: None,
730            log_message: Some("inventory={inventory}".into()),
731        };
732        let encoded = serde_json::to_value(breakpoint).unwrap();
733        assert_eq!(encoded["line"], 42);
734        assert_eq!(encoded["condition"], "inventory == 0");
735        assert!(encoded.get("hitCondition").is_none());
736    }
737
738    #[test]
739    fn real_debugpy_adapter_supports_breakpoint_state_and_continue() {
740        let Some(python) = std::env::var_os("GLASS_DEBUGPY_PYTHON") else {
741            return;
742        };
743        let root =
744            std::env::temp_dir().join(format!("glass-debugpy-fixture-{}", std::process::id()));
745        let _ = std::fs::remove_dir_all(&root);
746        std::fs::create_dir_all(&root).unwrap();
747        let program = root.join("program.py");
748        std::fs::write(&program, "value = 41\nanswer = value + 1\nprint(answer)\n").unwrap();
749        let config = DebugAdapterConfig::new(
750            PathBuf::from(python),
751            ["-m".to_string(), "debugpy.adapter".to_string()],
752        );
753        let mut debugger =
754            DebuggerSession::start(&root, &config, "Glass DebugPy E2E", Duration::from_secs(15))
755                .unwrap();
756        debugger
757            .launch(json!({
758                "name":"Glass debugpy fixture",
759                "type":"python",
760                "request":"launch",
761                "program":program,
762                "console":"internalConsole",
763                "justMyCode":false
764            }))
765            .unwrap();
766        let breakpoints = debugger.set_breakpoints(&program, &[2]).unwrap();
767        assert_eq!(breakpoints["breakpoints"][0]["verified"], true);
768        debugger.configuration_done().unwrap();
769        let stopped = wait_for_debug_event(&mut debugger, "stopped", Duration::from_secs(15));
770        let thread_id = stopped["threadId"].as_i64().unwrap();
771        let threads = debugger.threads().unwrap();
772        assert!(
773            threads["threads"]
774                .as_array()
775                .is_some_and(|items| !items.is_empty())
776        );
777        let stack = debugger.stack_trace(thread_id).unwrap();
778        let frame_id = stack["stackFrames"][0]["id"].as_i64().unwrap();
779        let scopes = debugger.scopes(frame_id).unwrap();
780        let variables_reference = scopes["scopes"][0]["variablesReference"].as_i64().unwrap();
781        let variables = debugger.variables(variables_reference).unwrap();
782        assert!(
783            variables["variables"]
784                .as_array()
785                .is_some_and(|items| { items.iter().any(|variable| variable["name"] == "value") })
786        );
787        let evaluated = debugger
788            .evaluate("value + 1", Some(frame_id), "watch")
789            .unwrap();
790        assert_eq!(evaluated["result"], "42");
791        debugger.continue_thread(thread_id).unwrap();
792        wait_for_debug_event(&mut debugger, "terminated", Duration::from_secs(15));
793        debugger.shutdown().unwrap();
794        let _ = std::fs::remove_dir_all(root);
795    }
796
797    fn wait_for_debug_event(
798        debugger: &mut DebuggerSession,
799        expected: &str,
800        timeout: Duration,
801    ) -> Value {
802        let deadline = Instant::now() + timeout;
803        loop {
804            for event in debugger.poll_events().unwrap() {
805                if event.event == expected {
806                    return event.body;
807                }
808            }
809            assert!(
810                Instant::now() < deadline,
811                "timed out waiting for {expected}"
812            );
813            std::thread::sleep(Duration::from_millis(10));
814        }
815    }
816}