Skip to main content

glass_dev/development/
cockpit.rs

1use super::{
2    Actor, DEVELOPMENT_SCHEMA_VERSION, DevelopmentError, DevelopmentEvent, DevelopmentEventKind,
3    DevelopmentResult, LocalHarness, ProjectDiff, ProjectWorkspace, Timeline, ToolAuthorization,
4    ToolCall,
5};
6use base64::Engine as _;
7use serde::{Deserialize, Serialize};
8use std::{
9    collections::BTreeMap,
10    fs::{self, OpenOptions},
11    io::{Read, Write},
12    net::{SocketAddr, TcpListener, TcpStream},
13    path::{Path, PathBuf},
14    sync::{
15        Arc,
16        atomic::{AtomicBool, Ordering},
17    },
18    thread::{self, JoinHandle},
19    time::{Duration, Instant, SystemTime, UNIX_EPOCH},
20};
21
22pub const MAX_RESIDENT_SESSIONS: usize = 8;
23pub const DEFAULT_SESSION_IDLE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
24pub const MAX_ATTENTION_ITEMS: usize = 32;
25pub const MAX_VERIFICATION_CHECKS: usize = 16;
26
27#[derive(Debug)]
28struct ResidentEntry {
29    workspace: ProjectWorkspace,
30    harness: LocalHarness,
31    last_used: Instant,
32}
33
34#[derive(Debug)]
35pub struct ResidentDevelopmentSessions {
36    entries: BTreeMap<PathBuf, ResidentEntry>,
37    capacity: usize,
38    idle_timeout: Duration,
39}
40
41impl Default for ResidentDevelopmentSessions {
42    fn default() -> Self {
43        Self::new(MAX_RESIDENT_SESSIONS, DEFAULT_SESSION_IDLE_TIMEOUT)
44    }
45}
46
47impl ResidentDevelopmentSessions {
48    pub fn new(capacity: usize, idle_timeout: Duration) -> Self {
49        Self {
50            entries: BTreeMap::new(),
51            capacity: capacity.clamp(1, MAX_RESIDENT_SESSIONS),
52            idle_timeout,
53        }
54    }
55
56    pub fn with_workspace<T>(
57        &mut self,
58        root: impl AsRef<Path>,
59        operation: impl FnOnce(&mut ProjectWorkspace) -> DevelopmentResult<T>,
60    ) -> DevelopmentResult<T> {
61        self.with_runtime(root, |workspace, _| operation(workspace))
62    }
63
64    pub fn with_runtime<T>(
65        &mut self,
66        root: impl AsRef<Path>,
67        operation: impl FnOnce(&mut ProjectWorkspace, &mut LocalHarness) -> DevelopmentResult<T>,
68    ) -> DevelopmentResult<T> {
69        let root = super::project::canonical_root(root.as_ref())?;
70        self.prune_idle();
71        if !self.entries.contains_key(&root) {
72            self.evict_lru_if_full();
73            self.entries.insert(
74                root.clone(),
75                ResidentEntry {
76                    workspace: ProjectWorkspace::open(&root)?,
77                    harness: LocalHarness::default(),
78                    last_used: Instant::now(),
79                },
80            );
81        }
82        let entry = self
83            .entries
84            .get_mut(&root)
85            .expect("resident entry inserted");
86        entry.last_used = Instant::now();
87        operation(&mut entry.workspace, &mut entry.harness)
88    }
89
90    pub fn contains(&mut self, root: impl AsRef<Path>) -> bool {
91        self.prune_idle();
92        super::project::canonical_root(root.as_ref())
93            .ok()
94            .is_some_and(|root| self.entries.contains_key(&root))
95    }
96
97    pub fn len(&self) -> usize {
98        self.entries.len()
99    }
100
101    pub fn is_empty(&self) -> bool {
102        self.entries.is_empty()
103    }
104
105    pub fn capacity(&self) -> usize {
106        self.capacity
107    }
108
109    pub fn detach(&mut self, root: impl AsRef<Path>) -> DevelopmentResult<bool> {
110        let root = super::project::canonical_root(root.as_ref())?;
111        Ok(self.entries.remove(&root).is_some())
112    }
113
114    pub fn roots(&self) -> Vec<PathBuf> {
115        self.entries.keys().cloned().collect()
116    }
117
118    fn prune_idle(&mut self) {
119        let now = Instant::now();
120        self.entries.retain(|_, entry| {
121            let has_running_process = entry
122                .workspace
123                .processes()
124                .list()
125                .iter()
126                .any(|process| matches!(process.state, super::ProcessState::Running));
127            has_running_process || now.duration_since(entry.last_used) < self.idle_timeout
128        });
129    }
130
131    fn evict_lru_if_full(&mut self) {
132        if self.entries.len() < self.capacity {
133            return;
134        }
135        if let Some(root) = self
136            .entries
137            .iter()
138            .min_by_key(|(_, entry)| entry.last_used)
139            .map(|(root, _)| root.clone())
140        {
141            self.entries.remove(&root);
142        }
143    }
144}
145
146#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
147#[serde(rename_all = "camelCase")]
148pub struct ReconnectCapsule {
149    pub schema_version: String,
150    pub project_root: String,
151    pub event_cursor: Option<String>,
152    pub mobile_view: Option<String>,
153    #[serde(default, skip_serializing_if = "Option::is_none")]
154    pub mobile_scroll: Option<u16>,
155    pub browser_target_id: Option<String>,
156    pub browser_revision: Option<u64>,
157    pub pending_attention: Option<String>,
158    pub live_mode: Option<String>,
159    pub live_quality: Option<String>,
160    pub saved_at_ms: u64,
161}
162
163impl ReconnectCapsule {
164    pub fn new(project_root: impl AsRef<Path>) -> DevelopmentResult<Self> {
165        let root = super::project::canonical_root(project_root.as_ref())?;
166        Ok(Self {
167            schema_version: DEVELOPMENT_SCHEMA_VERSION.into(),
168            project_root: root.display().to_string(),
169            event_cursor: None,
170            mobile_view: None,
171            mobile_scroll: None,
172            browser_target_id: None,
173            browser_revision: None,
174            pending_attention: None,
175            live_mode: None,
176            live_quality: None,
177            saved_at_ms: now_ms(),
178        })
179    }
180
181    pub fn validate(&self) -> DevelopmentResult<()> {
182        if self.schema_version != DEVELOPMENT_SCHEMA_VERSION {
183            return Err(DevelopmentError::InvalidInput(
184                "unsupported reconnect capsule schema".into(),
185            ));
186        }
187        for (name, value, limit) in [
188            ("projectRoot", Some(self.project_root.as_str()), 4096),
189            ("eventCursor", self.event_cursor.as_deref(), 128),
190            ("mobileView", self.mobile_view.as_deref(), 32),
191            ("browserTargetId", self.browser_target_id.as_deref(), 128),
192            ("pendingAttention", self.pending_attention.as_deref(), 256),
193            ("liveMode", self.live_mode.as_deref(), 32),
194            ("liveQuality", self.live_quality.as_deref(), 32),
195        ] {
196            if value.is_some_and(|value| value.len() > limit) {
197                return Err(DevelopmentError::InvalidInput(format!(
198                    "{name} exceeds the {limit} byte reconnect capsule limit"
199                )));
200            }
201        }
202        if self.mobile_view.as_deref().is_some_and(|value| {
203            !matches!(
204                value,
205                "home"
206                    | "overview"
207                    | "agent"
208                    | "app"
209                    | "browser"
210                    | "diff"
211                    | "project"
212                    | "process"
213                    | "logs"
214            )
215        }) {
216            return Err(DevelopmentError::InvalidInput(
217                "reconnect capsule mobileView is not recognized".into(),
218            ));
219        }
220        if self
221            .live_mode
222            .as_deref()
223            .is_some_and(|value| !matches!(value, "off" | "auto" | "on"))
224        {
225            return Err(DevelopmentError::InvalidInput(
226                "reconnect capsule liveMode is not recognized".into(),
227            ));
228        }
229        if self
230            .live_quality
231            .as_deref()
232            .is_some_and(|value| !matches!(value, "auto" | "data" | "balanced" | "smooth"))
233        {
234            return Err(DevelopmentError::InvalidInput(
235                "reconnect capsule liveQuality is not recognized".into(),
236            ));
237        }
238        let root = super::project::canonical_root(Path::new(&self.project_root))?;
239        if root != Path::new(&self.project_root) {
240            return Err(DevelopmentError::InvalidInput(
241                "reconnect capsule project root is not canonical".into(),
242            ));
243        }
244        Ok(())
245    }
246}
247
248pub struct ReconnectCapsuleStore;
249
250impl ReconnectCapsuleStore {
251    pub fn save(capsule: &ReconnectCapsule) -> DevelopmentResult<PathBuf> {
252        capsule.validate()?;
253        let path = capsule_path(Path::new(&capsule.project_root))?;
254        if let Some(parent) = path.parent() {
255            fs::create_dir_all(parent)?;
256        }
257        let temporary = path.with_extension(format!("json.tmp-{}", std::process::id()));
258        let mut file = OpenOptions::new()
259            .create_new(true)
260            .write(true)
261            .open(&temporary)?;
262        serde_json::to_writer_pretty(&mut file, capsule)?;
263        file.write_all(b"\n")?;
264        file.sync_all()?;
265        if let Err(error) = fs::rename(&temporary, &path) {
266            let _ = fs::remove_file(&temporary);
267            return Err(error.into());
268        }
269        Ok(path)
270    }
271
272    pub fn load(root: impl AsRef<Path>) -> DevelopmentResult<Option<ReconnectCapsule>> {
273        let path = capsule_path(root.as_ref())?;
274        if !path.is_file() {
275            return Ok(None);
276        }
277        let metadata = fs::metadata(&path)?;
278        if metadata.len() > 16 * 1024 {
279            return Err(DevelopmentError::InvalidInput(
280                "reconnect capsule exceeds 16384 bytes".into(),
281            ));
282        }
283        let capsule = serde_json::from_slice::<ReconnectCapsule>(&fs::read(path)?)?;
284        capsule.validate()?;
285        Ok(Some(capsule))
286    }
287
288    pub fn clear(root: impl AsRef<Path>) -> DevelopmentResult<bool> {
289        let path = capsule_path(root.as_ref())?;
290        if !path.exists() {
291            return Ok(false);
292        }
293        fs::remove_file(path)?;
294        Ok(true)
295    }
296}
297
298fn capsule_path(root: &Path) -> DevelopmentResult<PathBuf> {
299    let root = super::project::canonical_root(root)?;
300    Ok(Timeline::for_project(&root)?
301        .path()
302        .with_file_name("reconnect-capsule.json"))
303}
304
305#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
306#[serde(rename_all = "camelCase")]
307pub enum AttentionState {
308    NeedsAttention,
309    Running,
310    Recent,
311}
312
313#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
314#[serde(rename_all = "camelCase")]
315pub struct AttentionItem {
316    pub id: String,
317    pub state: AttentionState,
318    pub title: String,
319    pub detail: String,
320    pub occurred_at_ms: u64,
321    pub event_id: String,
322}
323
324pub fn attention_inbox(
325    events: impl DoubleEndedIterator<Item = DevelopmentEvent>,
326) -> Vec<AttentionItem> {
327    let mut items = events
328        .rev()
329        .filter_map(|event| attention_item(&event))
330        .take(MAX_ATTENTION_ITEMS)
331        .collect::<Vec<_>>();
332    items.sort_by_key(|item| std::cmp::Reverse(item.occurred_at_ms));
333    items
334}
335
336fn attention_item(event: &DevelopmentEvent) -> Option<AttentionItem> {
337    let (state, title, detail) = match event.kind {
338        DevelopmentEventKind::ProcessStarted => (
339            AttentionState::Running,
340            "Process running",
341            payload_label(&event.payload, "name", "managed process"),
342        ),
343        DevelopmentEventKind::TestStarted => (
344            AttentionState::Running,
345            "Tests running",
346            payload_label(&event.payload, "name", "test run"),
347        ),
348        DevelopmentEventKind::AgentPrompt => (
349            AttentionState::Running,
350            "Agent working",
351            "bounded local prompt accepted".into(),
352        ),
353        DevelopmentEventKind::DiagnosticsPublished
354            if event
355                .payload
356                .get("count")
357                .and_then(serde_json::Value::as_u64)
358                .unwrap_or(0)
359                > 0 =>
360        {
361            (
362                AttentionState::NeedsAttention,
363                "Diagnostics need attention",
364                payload_label(&event.payload, "path", "project diagnostics"),
365            )
366        }
367        DevelopmentEventKind::SemanticBreakpointHit => (
368            AttentionState::NeedsAttention,
369            "Semantic breakpoint hit",
370            payload_label(&event.payload, "entity", "browser entity changed"),
371        ),
372        DevelopmentEventKind::ProcessExited => {
373            let failed = event_failed(&event.payload);
374            (
375                if failed {
376                    AttentionState::NeedsAttention
377                } else {
378                    AttentionState::Recent
379                },
380                if failed {
381                    "Process failed"
382                } else {
383                    "Process completed"
384                },
385                payload_label(&event.payload, "name", "managed process"),
386            )
387        }
388        DevelopmentEventKind::TestCompleted => {
389            let failed = event_failed(&event.payload);
390            (
391                if failed {
392                    AttentionState::NeedsAttention
393                } else {
394                    AttentionState::Recent
395                },
396                if failed {
397                    "Tests failed"
398                } else {
399                    "Tests passed"
400                },
401                payload_label(&event.payload, "name", "test run"),
402            )
403        }
404        DevelopmentEventKind::VerificationCompleted => (
405            AttentionState::Recent,
406            "Verification completed",
407            payload_label(&event.payload, "status", "verification evidence updated"),
408        ),
409        DevelopmentEventKind::FileSaved => (
410            AttentionState::Recent,
411            "File saved",
412            payload_label(&event.payload, "path", "project file"),
413        ),
414        _ => return None,
415    };
416    Some(AttentionItem {
417        id: format!("attention:{}", event.id),
418        state,
419        title: title.into(),
420        detail,
421        occurred_at_ms: event.occurred_at_ms,
422        event_id: event.id.clone(),
423    })
424}
425
426fn event_failed(payload: &serde_json::Value) -> bool {
427    if payload.get("success").and_then(serde_json::Value::as_bool) == Some(false)
428        || payload
429            .get("code")
430            .and_then(serde_json::Value::as_i64)
431            .is_some_and(|code| code != 0)
432        || payload
433            .get("status")
434            .and_then(serde_json::Value::as_str)
435            .is_some_and(|status| matches!(status, "failed" | "timeout" | "cancelled"))
436    {
437        return true;
438    }
439    let Some(state) = payload.get("state") else {
440        return false;
441    };
442    state.as_str() == Some("failed")
443        || state
444            .get("exited")
445            .and_then(|exited| exited.get("code"))
446            .and_then(serde_json::Value::as_i64)
447            .is_some_and(|code| code != 0)
448}
449
450fn payload_label(payload: &serde_json::Value, field: &str, fallback: &str) -> String {
451    payload
452        .get(field)
453        .and_then(serde_json::Value::as_str)
454        .filter(|value| value.len() <= 256)
455        .unwrap_or(fallback)
456        .to_string()
457}
458
459#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
460#[serde(rename_all = "camelCase")]
461pub struct VerificationCheck {
462    pub label: String,
463    pub status: String,
464    pub detail: String,
465}
466
467#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
468#[serde(rename_all = "camelCase")]
469pub struct VerificationCard {
470    pub schema_version: String,
471    pub title: String,
472    pub outcome: String,
473    pub checks: Vec<VerificationCheck>,
474    pub changed_files: usize,
475    pub semantic_revision: Option<u64>,
476    pub visual_status: String,
477    pub generated_at_ms: u64,
478}
479
480impl VerificationCard {
481    pub fn from_diff(
482        title: &str,
483        diff: &ProjectDiff,
484        semantic_revision: Option<u64>,
485    ) -> DevelopmentResult<Self> {
486        if title.trim().is_empty() || title.len() > 128 {
487            return Err(DevelopmentError::InvalidInput(
488                "verification card title must be 1-128 bytes".into(),
489            ));
490        }
491        let visual_status = diff
492            .visual
493            .get("status")
494            .and_then(serde_json::Value::as_str)
495            .unwrap_or("not-captured")
496            .to_string();
497        let process_count = diff
498            .runtime
499            .get("processCount")
500            .and_then(serde_json::Value::as_u64)
501            .unwrap_or(0);
502        let link_count = diff
503            .semantic
504            .get("linkCount")
505            .and_then(serde_json::Value::as_u64)
506            .unwrap_or(0);
507        Ok(Self {
508            schema_version: DEVELOPMENT_SCHEMA_VERSION.into(),
509            title: title.into(),
510            outcome: "reviewRequired".into(),
511            checks: vec![
512                VerificationCheck {
513                    label: "Code changes".into(),
514                    status: if diff.files.is_empty() {
515                        "clean"
516                    } else {
517                        "changed"
518                    }
519                    .into(),
520                    detail: format!("{} changed files", diff.files.len()),
521                },
522                VerificationCheck {
523                    label: "Runtime".into(),
524                    status: "observed".into(),
525                    detail: format!("{process_count} managed processes"),
526                },
527                VerificationCheck {
528                    label: "Semantic links".into(),
529                    status: "observed".into(),
530                    detail: format!("{link_count} source/runtime links"),
531                },
532                VerificationCheck {
533                    label: "Visual evidence".into(),
534                    status: visual_status.clone(),
535                    detail: if visual_status == "not-captured" {
536                        "request an explicit screenshot or comparison".into()
537                    } else {
538                        "explicit visual evidence attached".into()
539                    },
540                },
541            ],
542            changed_files: diff.files.len(),
543            semantic_revision,
544            visual_status,
545            generated_at_ms: now_ms(),
546        })
547    }
548
549    pub fn add_check(&mut self, check: VerificationCheck) -> DevelopmentResult<()> {
550        if self.checks.len() == MAX_VERIFICATION_CHECKS {
551            return Err(DevelopmentError::InvalidInput(
552                "verification card check limit reached".into(),
553            ));
554        }
555        if check.label.is_empty() || check.label.len() > 128 || check.detail.len() > 512 {
556            return Err(DevelopmentError::InvalidInput(
557                "verification check exceeds bounded text limits".into(),
558            ));
559        }
560        self.checks.push(check);
561        Ok(())
562    }
563}
564const MAX_COCKPIT_REQUEST_BYTES: usize = 128 * 1024;
565const MAX_COCKPIT_RESPONSE_BYTES: usize = 512 * 1024;
566
567/// A loopback-only HTTP cockpit for private local inspection and commands.
568///
569/// The token is part of the URL, the listener binds only to `127.0.0.1`, and
570/// every request is bounded before it reaches the resident workspace. This is
571/// intentionally not a public remote-view transport; use SSH/Mosh port
572/// forwarding when the operator is remote.
573#[derive(Debug)]
574pub struct LocalCockpit {
575    address: SocketAddr,
576    token: String,
577    stop: Arc<AtomicBool>,
578    join: Option<JoinHandle<()>>,
579}
580
581impl LocalCockpit {
582    pub fn start(workspace: crate::SharedDevelopmentWorkspace) -> DevelopmentResult<Self> {
583        let listener = TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))?;
584        listener.set_nonblocking(true)?;
585        let address = listener.local_addr()?;
586        let token = cockpit_token()?;
587        let stop = Arc::new(AtomicBool::new(false));
588        let thread_stop = Arc::clone(&stop);
589        let thread_token = token.clone();
590        let join = thread::Builder::new()
591            .name("glass-private-cockpit".into())
592            .spawn(move || cockpit_loop(listener, workspace, thread_token, thread_stop))
593            .map_err(|error| {
594                DevelopmentError::Process(format!("failed to start private cockpit: {error}"))
595            })?;
596        Ok(Self {
597            address,
598            token,
599            stop,
600            join: Some(join),
601        })
602    }
603
604    pub fn address(&self) -> SocketAddr {
605        self.address
606    }
607
608    pub fn token(&self) -> &str {
609        &self.token
610    }
611
612    pub fn local_url(&self) -> String {
613        format!("http://{}/{}/", self.address, self.token)
614    }
615
616    pub fn shutdown(&mut self) {
617        self.stop.store(true, Ordering::Release);
618        if let Some(join) = self.join.take() {
619            let _ = join.join();
620        }
621    }
622}
623
624impl Drop for LocalCockpit {
625    fn drop(&mut self) {
626        self.shutdown();
627    }
628}
629
630#[derive(Debug, Deserialize)]
631#[serde(rename_all = "camelCase")]
632struct CockpitCommandRequest {
633    name: String,
634    #[serde(default)]
635    arguments: serde_json::Value,
636    #[serde(default)]
637    allow_mutation: bool,
638    #[serde(default)]
639    confirmed: bool,
640    expected_generation: Option<u64>,
641    expected_project_revision: Option<u64>,
642}
643
644fn cockpit_loop(
645    listener: TcpListener,
646    workspace: crate::SharedDevelopmentWorkspace,
647    token: String,
648    stop: Arc<AtomicBool>,
649) {
650    let mut github_probe = crate::github::GitHubProbeCache::default();
651    while !stop.load(Ordering::Acquire) {
652        match listener.accept() {
653            Ok((mut stream, _)) => {
654                let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
655                let response =
656                    handle_cockpit_connection(&mut stream, &workspace, &token, &mut github_probe);
657                write_http_response(&mut stream, response);
658            }
659            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
660                thread::sleep(Duration::from_millis(25));
661            }
662            Err(_) => break,
663        }
664    }
665}
666
667fn handle_cockpit_connection(
668    stream: &mut TcpStream,
669    workspace: &crate::SharedDevelopmentWorkspace,
670    token: &str,
671    github_probe: &mut crate::github::GitHubProbeCache,
672) -> (u16, &'static str, Vec<u8>) {
673    let request = match read_http_request(stream) {
674        Ok(request) => request,
675        Err(error) => return json_http(400, serde_json::json!({"error":error})),
676    };
677    let (method, path, body) = request;
678    let prefix = format!("/{token}");
679    if !path.starts_with(&prefix) || !path[prefix.len()..].strip_prefix('/').is_some_and(|_| true) {
680        return json_http(
681            401,
682            serde_json::json!({"error":"private cockpit token required"}),
683        );
684    }
685    let endpoint = path[prefix.len()..].split('?').next().unwrap_or_default();
686    match (method.as_str(), endpoint) {
687        ("GET", "/") => (
688            200,
689            "text/html; charset=utf-8",
690            cockpit_html(&format!("/{token}/")).into_bytes(),
691        ),
692        ("GET", "/v1/health") => json_http(200, serde_json::json!({"ok":true})),
693        ("GET", "/v1/state") => match cockpit_state(workspace, github_probe) {
694            Ok(value) => json_http(200, value),
695            Err(error) => json_http(503, serde_json::json!({"error":error.to_string()})),
696        },
697        ("POST", "/v1/command") => match cockpit_command(workspace, &body) {
698            Ok(value) => json_http(200, value),
699            Err(error) => {
700                let status = if matches!(error, DevelopmentError::Conflict(_)) {
701                    409
702                } else {
703                    400
704                };
705                json_http(status, serde_json::json!({"error":error.to_string()}))
706            }
707        },
708        _ => json_http(
709            404,
710            serde_json::json!({"error":"cockpit endpoint not found"}),
711        ),
712    }
713}
714
715fn read_http_request(stream: &mut TcpStream) -> Result<(String, String, Vec<u8>), String> {
716    let mut bytes = Vec::with_capacity(4096);
717    let mut chunk = [0_u8; 4096];
718    let header_end = loop {
719        let read = stream.read(&mut chunk).map_err(|error| error.to_string())?;
720        if read == 0 {
721            return Err("request ended before headers".into());
722        }
723        bytes.extend_from_slice(&chunk[..read]);
724        if bytes.len() > MAX_COCKPIT_REQUEST_BYTES {
725            return Err("request exceeds the private cockpit limit".into());
726        }
727        if let Some(index) = bytes.windows(4).position(|window| window == b"\r\n\r\n") {
728            break index + 4;
729        }
730    };
731    let header = std::str::from_utf8(&bytes[..header_end])
732        .map_err(|_| "request headers are not UTF-8".to_string())?;
733    let mut lines = header.split("\r\n");
734    let request_line = lines.next().ok_or("request line missing")?;
735    let mut request_parts = request_line.split_whitespace();
736    let method = request_parts
737        .next()
738        .ok_or("request method missing")?
739        .to_string();
740    let path = request_parts
741        .next()
742        .ok_or("request path missing")?
743        .to_string();
744    if request_parts.next().is_none() {
745        return Err("HTTP version missing".into());
746    }
747    let mut content_length = 0usize;
748    for line in lines {
749        if let Some((name, value)) = line.split_once(':')
750            && name.eq_ignore_ascii_case("content-length")
751        {
752            content_length = value
753                .trim()
754                .parse()
755                .map_err(|_| "invalid content length".to_string())?;
756        }
757    }
758    if content_length > MAX_COCKPIT_REQUEST_BYTES - header_end {
759        return Err("request body exceeds the private cockpit limit".into());
760    }
761    while bytes.len() < header_end + content_length {
762        let read = stream.read(&mut chunk).map_err(|error| error.to_string())?;
763        if read == 0 {
764            return Err("request ended before body".into());
765        }
766        bytes.extend_from_slice(&chunk[..read]);
767    }
768    Ok((
769        method,
770        path,
771        bytes[header_end..header_end + content_length].to_vec(),
772    ))
773}
774
775fn cockpit_state(
776    workspace: &crate::SharedDevelopmentWorkspace,
777    github_probe: &mut crate::github::GitHubProbeCache,
778) -> DevelopmentResult<serde_json::Value> {
779    let (root, generation, revision, trust, agents, tasks, git) = {
780        let mut locked = workspace.lock()?;
781        let root = locked.root().display().to_string();
782        let generation = locked.generation();
783        let revision = locked.project().revision();
784        let trust = locked.trust().label().to_string();
785        let agents = locked.agents().list().map_err(|error| error.to_string());
786        let tasks = locked.task_snapshots().map_err(|error| error.to_string());
787        let git = locked
788            .git()
789            .map(|git| git.status().map_err(|error| error.to_string()));
790        (root, generation, revision, trust, agents, tasks, git)
791    };
792    let github = github_probe.probe(Path::new(&root));
793    let agents = match agents {
794        Ok(value) => serde_json::to_value(value)?,
795        Err(error) => serde_json::json!({"error":error}),
796    };
797    let tasks = match tasks {
798        Ok(value) => serde_json::to_value(value)?,
799        Err(error) => serde_json::json!({"error":error}),
800    };
801    let git = match git {
802        Some(Ok(value)) => serde_json::to_value(value)?,
803        Some(Err(error)) => serde_json::json!({"error":error}),
804        None => serde_json::Value::Null,
805    };
806    Ok(serde_json::json!({
807        "schemaVersion": super::DEVELOPMENT_COCKPIT_SCHEMA_VERSION,
808        "root": root,
809        "generation": generation,
810        "projectRevision": revision,
811        "trust": trust,
812        "agents": agents,
813        "tasks": tasks,
814        "git": git,
815        "github": github,
816    }))
817}
818fn cockpit_command(
819    workspace: &crate::SharedDevelopmentWorkspace,
820    body: &[u8],
821) -> DevelopmentResult<serde_json::Value> {
822    let request: CockpitCommandRequest = serde_json::from_slice(body)?;
823    if request.name.is_empty()
824        || request.name.len() > 128
825        || !request
826            .name
827            .bytes()
828            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'-' | b'_'))
829    {
830        return Err(DevelopmentError::InvalidInput(
831            "cockpit command names must be bounded tool identifiers".into(),
832        ));
833    }
834    let mut locked = workspace.lock()?;
835    let call = ToolCall {
836        id: format!("cockpit-{}", now_ms()),
837        name: request.name,
838        arguments: request.arguments,
839    };
840    let expected_generation = request.expected_generation.unwrap_or(locked.generation());
841    let expected_project_revision = request
842        .expected_project_revision
843        .unwrap_or_else(|| locked.project().revision());
844    let context = crate::tools::DevelopmentToolContext {
845        authorization: ToolAuthorization {
846            actor: Actor::external("cockpit"),
847            allow_mutation: request.allow_mutation && request.confirmed,
848            confirmed: request.confirmed,
849        },
850        initiator: None,
851        expected_generation,
852        expected_project_revision,
853    };
854    let result = locked.execute_tool(&call, &context)?;
855    Ok(serde_json::json!({"ok":true,"tool":call.name,"result":result}))
856}
857
858fn write_http_response(stream: &mut TcpStream, response: (u16, &'static str, Vec<u8>)) {
859    let (status, content_type, body) = response;
860    let reason = match status {
861        200 => "OK",
862        400 => "Bad Request",
863        401 => "Unauthorized",
864        404 => "Not Found",
865        409 => "Conflict",
866        503 => "Service Unavailable",
867        _ => "Error",
868    };
869    let header = format!(
870        "HTTP/1.1 {status} {reason}\r\nContent-Type: {content_type}\r\nContent-Length: {}\r\nCache-Control: no-store\r\nConnection: close\r\n\r\n",
871        body.len()
872    );
873    let _ = stream.write_all(header.as_bytes());
874    let _ = stream.write_all(&body);
875}
876
877fn json_http(status: u16, value: serde_json::Value) -> (u16, &'static str, Vec<u8>) {
878    let body = serde_json::to_vec(&value)
879        .unwrap_or_else(|_| b"{\"error\":\"serialization failure\"}".to_vec());
880    if body.len() > MAX_COCKPIT_RESPONSE_BYTES {
881        return (
882            503,
883            "application/json",
884            b"{\"error\":\"cockpit response exceeded its limit\"}".to_vec(),
885        );
886    }
887    (status, "application/json", body)
888}
889
890fn cockpit_token() -> DevelopmentResult<String> {
891    let mut bytes = [0_u8; 24];
892    getrandom::fill(&mut bytes).map_err(|error| {
893        DevelopmentError::Process(format!("private cockpit token generation failed: {error}"))
894    })?;
895    Ok(base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(bytes))
896}
897
898fn cockpit_html(base: &str) -> String {
899    format!(
900        r##"<!doctype html>
901<meta charset="utf-8">
902<title>Glass private cockpit</title>
903<style>
904body{{font:15px/1.45 system-ui,sans-serif;background:#10131a;color:#e8edf5;margin:2rem;max-width:72rem}}
905pre{{background:#181d27;padding:1rem;border-radius:.6rem;white-space:pre-wrap}}
906button,input{{font:inherit;padding:.45rem .7rem;margin:.2rem 0}}
907button{{cursor:pointer}} code{{color:#9ad1ff}}
908</style>
909<h1>Glass private cockpit</h1>
910<p>Loopback-only workspace state. Mutations remain governed by Glass trust and revision checks.</p>
911<p><button id="refresh">Refresh</button>
912<button id="review">Review GitHub PR</button></p>
913<pre id="state">Loading…</pre>
914const base = "{}";
915const state = document.querySelector("#state");
916async function load() {{
917  const response = await fetch(base + "v1/state", {{cache:"no-store"}});
918  state.textContent = JSON.stringify(await response.json(), null, 2);
919}}
920async function command(name, argumentsValue={{}}) {{
921  const response = await fetch(base + "v1/command", {{
922    method:"POST", headers:{{"content-type":"application/json"}},
923    body:JSON.stringify({{name, arguments:argumentsValue}})
924  }});
925  state.textContent = JSON.stringify(await response.json(), null, 2);
926  await load();
927}}
928document.querySelector("#refresh").onclick = load;
929document.querySelector("#review").onclick = () => command("glass.github.review");
930load();
931</script>"##,
932        base
933    )
934}
935
936fn now_ms() -> u64 {
937    SystemTime::now()
938        .duration_since(UNIX_EPOCH)
939        .map_or(0, |duration| duration.as_millis() as u64)
940}
941
942#[cfg(test)]
943mod tests {
944    use super::*;
945
946    fn fixture(name: &str) -> PathBuf {
947        let root =
948            std::env::temp_dir().join(format!("glass-cockpit-{name}-{}", std::process::id()));
949        let _ = fs::remove_dir_all(&root);
950        fs::create_dir_all(&root).unwrap();
951        fs::write(
952            root.join("Cargo.toml"),
953            "[package]\nname='demo'\nversion='0.1.0'\n",
954        )
955        .unwrap();
956        root
957    }
958
959    #[test]
960    fn resident_registry_reuses_and_evicts_bounded_workspaces() {
961        let first = fixture("first");
962        let second = fixture("second");
963        let mut sessions = ResidentDevelopmentSessions::new(1, Duration::from_secs(60));
964        sessions
965            .with_workspace(&first, |workspace| {
966                workspace.attach_actor(super::super::Actor::external("one"))?;
967                Ok(())
968            })
969            .unwrap();
970        sessions
971            .with_workspace(&first, |workspace| {
972                assert!(workspace.actors().any(|actor| actor.id == "external:one"));
973                Ok(())
974            })
975            .unwrap();
976        sessions.with_workspace(&second, |_| Ok(())).unwrap();
977        assert_eq!(sessions.len(), 1);
978        assert!(!sessions.contains(&first));
979        assert!(sessions.contains(&second));
980        let _ = fs::remove_dir_all(first);
981        let _ = fs::remove_dir_all(second);
982    }
983
984    #[test]
985    fn reconnect_capsule_round_trips_without_payload_fields() {
986        let root = fixture("capsule");
987        let mut capsule = ReconnectCapsule::new(&root).unwrap();
988        capsule.event_cursor = Some("dev-1".into());
989        capsule.mobile_view = Some("app".into());
990        capsule.mobile_scroll = Some(20);
991        ReconnectCapsuleStore::save(&capsule).unwrap();
992        assert_eq!(ReconnectCapsuleStore::load(&root).unwrap(), Some(capsule));
993        assert!(ReconnectCapsuleStore::clear(&root).unwrap());
994        assert_eq!(ReconnectCapsuleStore::load(&root).unwrap(), None);
995        let _ = fs::remove_dir_all(root);
996    }
997
998    #[test]
999    fn reconnect_capsule_accepts_current_and_legacy_mobile_views() {
1000        let root = fixture("capsule-mobile-views");
1001        for view in [
1002            "home", "overview", "agent", "app", "browser", "diff", "project", "process", "logs",
1003        ] {
1004            let mut capsule = ReconnectCapsule::new(&root).unwrap();
1005            capsule.mobile_view = Some(view.into());
1006            capsule.validate().unwrap();
1007        }
1008        let mut capsule = ReconnectCapsule::new(&root).unwrap();
1009        capsule.mobile_view = Some("unknown".into());
1010        assert!(capsule.validate().is_err());
1011        let _ = fs::remove_dir_all(root);
1012    }
1013
1014    #[test]
1015    fn resident_registry_expires_idle_state_before_reopening() {
1016        let root = fixture("expiry");
1017        fs::write(root.join("src.rs"), "fn main() {}\n").unwrap();
1018        let mut sessions = ResidentDevelopmentSessions::new(2, Duration::ZERO);
1019        sessions
1020            .with_workspace(&root, |workspace| {
1021                workspace.open_buffer("src.rs", super::super::Actor::local())?;
1022                Ok(())
1023            })
1024            .unwrap();
1025        let retained = sessions
1026            .with_workspace(&root, |workspace| Ok(workspace.buffer("src.rs").is_some()))
1027            .unwrap();
1028        assert!(!retained);
1029        let _ = fs::remove_dir_all(root);
1030    }
1031
1032    #[test]
1033    fn attention_inbox_classifies_only_actionable_runtime_events() {
1034        let events = vec![
1035            DevelopmentEvent::new(
1036                super::super::Actor::local(),
1037                DevelopmentEventKind::WorkspaceOpened,
1038                "/tmp",
1039                serde_json::json!({}),
1040                1,
1041            ),
1042            DevelopmentEvent::new(
1043                super::super::Actor::local(),
1044                DevelopmentEventKind::DiagnosticsPublished,
1045                "/tmp",
1046                serde_json::json!({"count":2,"path":"src/lib.rs"}),
1047                2,
1048            ),
1049            DevelopmentEvent::new(
1050                super::super::Actor::local(),
1051                DevelopmentEventKind::ProcessStarted,
1052                "/tmp",
1053                serde_json::json!({"name":"dev"}),
1054                3,
1055            ),
1056            DevelopmentEvent::new(
1057                super::super::Actor::local(),
1058                DevelopmentEventKind::TestCompleted,
1059                "/tmp",
1060                serde_json::json!({"name":"unit","state":{"exited":{"code":1}}}),
1061                4,
1062            ),
1063        ];
1064        let inbox = attention_inbox(events.into_iter());
1065        assert_eq!(inbox.len(), 3);
1066        assert!(
1067            inbox
1068                .iter()
1069                .any(|item| item.state == AttentionState::Running)
1070        );
1071        assert!(inbox.iter().any(|item| item.title == "Tests failed"));
1072    }
1073
1074    #[test]
1075    fn local_cockpit_requires_token_and_serves_health() {
1076        let root = fixture("http");
1077        let workspace = crate::SharedDevelopmentWorkspace::open(&root).unwrap();
1078        let cockpit = LocalCockpit::start(workspace).unwrap();
1079
1080        let mut unauthorized = TcpStream::connect(cockpit.address()).unwrap();
1081        unauthorized
1082            .write_all(b"GET /v1/health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
1083            .unwrap();
1084        unauthorized.shutdown(std::net::Shutdown::Write).unwrap();
1085        let mut unauthorized_response = Vec::new();
1086        unauthorized
1087            .read_to_end(&mut unauthorized_response)
1088            .unwrap();
1089        let unauthorized_response = String::from_utf8_lossy(&unauthorized_response);
1090        assert!(unauthorized_response.starts_with("HTTP/1.1 401 Unauthorized"));
1091
1092        let request = format!(
1093            "GET /{}/v1/health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n",
1094            cockpit.token()
1095        );
1096        let mut authorized = TcpStream::connect(cockpit.address()).unwrap();
1097        authorized.write_all(request.as_bytes()).unwrap();
1098        authorized.shutdown(std::net::Shutdown::Write).unwrap();
1099        let mut authorized_response = Vec::new();
1100        authorized.read_to_end(&mut authorized_response).unwrap();
1101        let authorized_response = String::from_utf8_lossy(&authorized_response);
1102        assert!(authorized_response.starts_with("HTTP/1.1 200 OK"));
1103        assert!(authorized_response.contains("{\"ok\":true}"));
1104        drop(cockpit);
1105        let _ = fs::remove_dir_all(root);
1106    }
1107
1108    #[test]
1109    fn verification_card_keeps_visual_evidence_explicit() {
1110        let diff = ProjectDiff {
1111            schema_version: DEVELOPMENT_SCHEMA_VERSION.into(),
1112            files: vec![],
1113            runtime: BTreeMap::from([("processCount".into(), serde_json::json!(1))]),
1114            semantic: BTreeMap::from([("linkCount".into(), serde_json::json!(2))]),
1115            visual: BTreeMap::from([("status".into(), serde_json::json!("not-captured"))]),
1116            workflow: BTreeMap::new(),
1117            test_impact: BTreeMap::new(),
1118        };
1119        let card = VerificationCard::from_diff("Checkout fix", &diff, Some(9)).unwrap();
1120        assert_eq!(card.visual_status, "not-captured");
1121        assert_eq!(card.checks.len(), 4);
1122        assert!(card.checks[3].detail.contains("explicit screenshot"));
1123    }
1124}