1use super::{
2 DEVELOPMENT_SCHEMA_VERSION, DevelopmentError, DevelopmentEvent, DevelopmentEventKind,
3 DevelopmentResult, LocalHarness, ProjectDiff, ProjectWorkspace, Timeline,
4};
5use serde::{Deserialize, Serialize};
6use std::{
7 collections::BTreeMap,
8 fs::{self, OpenOptions},
9 io::Write,
10 path::{Path, PathBuf},
11 time::{Duration, Instant, SystemTime, UNIX_EPOCH},
12};
13
14pub const MAX_RESIDENT_SESSIONS: usize = 8;
15pub const DEFAULT_SESSION_IDLE_TIMEOUT: Duration = Duration::from_secs(30 * 60);
16pub const MAX_ATTENTION_ITEMS: usize = 32;
17pub const MAX_VERIFICATION_CHECKS: usize = 16;
18
19#[derive(Debug)]
20struct ResidentEntry {
21 workspace: ProjectWorkspace,
22 harness: LocalHarness,
23 last_used: Instant,
24}
25
26#[derive(Debug)]
27pub struct ResidentDevelopmentSessions {
28 entries: BTreeMap<PathBuf, ResidentEntry>,
29 capacity: usize,
30 idle_timeout: Duration,
31}
32
33impl Default for ResidentDevelopmentSessions {
34 fn default() -> Self {
35 Self::new(MAX_RESIDENT_SESSIONS, DEFAULT_SESSION_IDLE_TIMEOUT)
36 }
37}
38
39impl ResidentDevelopmentSessions {
40 pub fn new(capacity: usize, idle_timeout: Duration) -> Self {
41 Self {
42 entries: BTreeMap::new(),
43 capacity: capacity.clamp(1, MAX_RESIDENT_SESSIONS),
44 idle_timeout,
45 }
46 }
47
48 pub fn with_workspace<T>(
49 &mut self,
50 root: impl AsRef<Path>,
51 operation: impl FnOnce(&mut ProjectWorkspace) -> DevelopmentResult<T>,
52 ) -> DevelopmentResult<T> {
53 self.with_runtime(root, |workspace, _| operation(workspace))
54 }
55
56 pub fn with_runtime<T>(
57 &mut self,
58 root: impl AsRef<Path>,
59 operation: impl FnOnce(&mut ProjectWorkspace, &mut LocalHarness) -> DevelopmentResult<T>,
60 ) -> DevelopmentResult<T> {
61 let root = super::project::canonical_root(root.as_ref())?;
62 self.prune_idle();
63 if !self.entries.contains_key(&root) {
64 self.evict_lru_if_full();
65 self.entries.insert(
66 root.clone(),
67 ResidentEntry {
68 workspace: ProjectWorkspace::open(&root)?,
69 harness: LocalHarness::default(),
70 last_used: Instant::now(),
71 },
72 );
73 }
74 let entry = self
75 .entries
76 .get_mut(&root)
77 .expect("resident entry inserted");
78 entry.last_used = Instant::now();
79 operation(&mut entry.workspace, &mut entry.harness)
80 }
81
82 pub fn contains(&mut self, root: impl AsRef<Path>) -> bool {
83 self.prune_idle();
84 super::project::canonical_root(root.as_ref())
85 .ok()
86 .is_some_and(|root| self.entries.contains_key(&root))
87 }
88
89 pub fn len(&self) -> usize {
90 self.entries.len()
91 }
92
93 pub fn is_empty(&self) -> bool {
94 self.entries.is_empty()
95 }
96
97 pub fn capacity(&self) -> usize {
98 self.capacity
99 }
100
101 pub fn detach(&mut self, root: impl AsRef<Path>) -> DevelopmentResult<bool> {
102 let root = super::project::canonical_root(root.as_ref())?;
103 Ok(self.entries.remove(&root).is_some())
104 }
105
106 pub fn roots(&self) -> Vec<PathBuf> {
107 self.entries.keys().cloned().collect()
108 }
109
110 fn prune_idle(&mut self) {
111 let now = Instant::now();
112 self.entries.retain(|_, entry| {
113 let has_running_process = entry
114 .workspace
115 .processes()
116 .list()
117 .iter()
118 .any(|process| matches!(process.state, super::ProcessState::Running));
119 has_running_process || now.duration_since(entry.last_used) < self.idle_timeout
120 });
121 }
122
123 fn evict_lru_if_full(&mut self) {
124 if self.entries.len() < self.capacity {
125 return;
126 }
127 if let Some(root) = self
128 .entries
129 .iter()
130 .min_by_key(|(_, entry)| entry.last_used)
131 .map(|(root, _)| root.clone())
132 {
133 self.entries.remove(&root);
134 }
135 }
136}
137
138#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
139#[serde(rename_all = "camelCase")]
140pub struct ReconnectCapsule {
141 pub schema_version: String,
142 pub project_root: String,
143 pub event_cursor: Option<String>,
144 pub mobile_view: Option<String>,
145 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub mobile_scroll: Option<u16>,
147 pub browser_target_id: Option<String>,
148 pub browser_revision: Option<u64>,
149 pub pending_attention: Option<String>,
150 pub live_mode: Option<String>,
151 pub live_quality: Option<String>,
152 pub saved_at_ms: u64,
153}
154
155impl ReconnectCapsule {
156 pub fn new(project_root: impl AsRef<Path>) -> DevelopmentResult<Self> {
157 let root = super::project::canonical_root(project_root.as_ref())?;
158 Ok(Self {
159 schema_version: DEVELOPMENT_SCHEMA_VERSION.into(),
160 project_root: root.display().to_string(),
161 event_cursor: None,
162 mobile_view: None,
163 mobile_scroll: None,
164 browser_target_id: None,
165 browser_revision: None,
166 pending_attention: None,
167 live_mode: None,
168 live_quality: None,
169 saved_at_ms: now_ms(),
170 })
171 }
172
173 pub fn validate(&self) -> DevelopmentResult<()> {
174 if self.schema_version != DEVELOPMENT_SCHEMA_VERSION {
175 return Err(DevelopmentError::InvalidInput(
176 "unsupported reconnect capsule schema".into(),
177 ));
178 }
179 for (name, value, limit) in [
180 ("projectRoot", Some(self.project_root.as_str()), 4096),
181 ("eventCursor", self.event_cursor.as_deref(), 128),
182 ("mobileView", self.mobile_view.as_deref(), 32),
183 ("browserTargetId", self.browser_target_id.as_deref(), 128),
184 ("pendingAttention", self.pending_attention.as_deref(), 256),
185 ("liveMode", self.live_mode.as_deref(), 32),
186 ("liveQuality", self.live_quality.as_deref(), 32),
187 ] {
188 if value.is_some_and(|value| value.len() > limit) {
189 return Err(DevelopmentError::InvalidInput(format!(
190 "{name} exceeds the {limit} byte reconnect capsule limit"
191 )));
192 }
193 }
194 if self.mobile_view.as_deref().is_some_and(|value| {
195 !matches!(
196 value,
197 "home"
198 | "overview"
199 | "agent"
200 | "app"
201 | "browser"
202 | "diff"
203 | "project"
204 | "process"
205 | "logs"
206 )
207 }) {
208 return Err(DevelopmentError::InvalidInput(
209 "reconnect capsule mobileView is not recognized".into(),
210 ));
211 }
212 if self
213 .live_mode
214 .as_deref()
215 .is_some_and(|value| !matches!(value, "off" | "auto" | "on"))
216 {
217 return Err(DevelopmentError::InvalidInput(
218 "reconnect capsule liveMode is not recognized".into(),
219 ));
220 }
221 if self
222 .live_quality
223 .as_deref()
224 .is_some_and(|value| !matches!(value, "auto" | "data" | "balanced" | "smooth"))
225 {
226 return Err(DevelopmentError::InvalidInput(
227 "reconnect capsule liveQuality is not recognized".into(),
228 ));
229 }
230 let root = super::project::canonical_root(Path::new(&self.project_root))?;
231 if root != Path::new(&self.project_root) {
232 return Err(DevelopmentError::InvalidInput(
233 "reconnect capsule project root is not canonical".into(),
234 ));
235 }
236 Ok(())
237 }
238}
239
240pub struct ReconnectCapsuleStore;
241
242impl ReconnectCapsuleStore {
243 pub fn save(capsule: &ReconnectCapsule) -> DevelopmentResult<PathBuf> {
244 capsule.validate()?;
245 let path = capsule_path(Path::new(&capsule.project_root))?;
246 if let Some(parent) = path.parent() {
247 fs::create_dir_all(parent)?;
248 }
249 let temporary = path.with_extension(format!("json.tmp-{}", std::process::id()));
250 let mut file = OpenOptions::new()
251 .create_new(true)
252 .write(true)
253 .open(&temporary)?;
254 serde_json::to_writer_pretty(&mut file, capsule)?;
255 file.write_all(b"\n")?;
256 file.sync_all()?;
257 if let Err(error) = fs::rename(&temporary, &path) {
258 let _ = fs::remove_file(&temporary);
259 return Err(error.into());
260 }
261 Ok(path)
262 }
263
264 pub fn load(root: impl AsRef<Path>) -> DevelopmentResult<Option<ReconnectCapsule>> {
265 let path = capsule_path(root.as_ref())?;
266 if !path.is_file() {
267 return Ok(None);
268 }
269 let metadata = fs::metadata(&path)?;
270 if metadata.len() > 16 * 1024 {
271 return Err(DevelopmentError::InvalidInput(
272 "reconnect capsule exceeds 16384 bytes".into(),
273 ));
274 }
275 let capsule = serde_json::from_slice::<ReconnectCapsule>(&fs::read(path)?)?;
276 capsule.validate()?;
277 Ok(Some(capsule))
278 }
279
280 pub fn clear(root: impl AsRef<Path>) -> DevelopmentResult<bool> {
281 let path = capsule_path(root.as_ref())?;
282 if !path.exists() {
283 return Ok(false);
284 }
285 fs::remove_file(path)?;
286 Ok(true)
287 }
288}
289
290fn capsule_path(root: &Path) -> DevelopmentResult<PathBuf> {
291 let root = super::project::canonical_root(root)?;
292 Ok(Timeline::for_project(&root)?
293 .path()
294 .with_file_name("reconnect-capsule.json"))
295}
296
297#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
298#[serde(rename_all = "camelCase")]
299pub enum AttentionState {
300 NeedsAttention,
301 Running,
302 Recent,
303}
304
305#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
306#[serde(rename_all = "camelCase")]
307pub struct AttentionItem {
308 pub id: String,
309 pub state: AttentionState,
310 pub title: String,
311 pub detail: String,
312 pub occurred_at_ms: u64,
313 pub event_id: String,
314}
315
316pub fn attention_inbox(
317 events: impl DoubleEndedIterator<Item = DevelopmentEvent>,
318) -> Vec<AttentionItem> {
319 let mut items = events
320 .rev()
321 .filter_map(|event| attention_item(&event))
322 .take(MAX_ATTENTION_ITEMS)
323 .collect::<Vec<_>>();
324 items.sort_by_key(|item| std::cmp::Reverse(item.occurred_at_ms));
325 items
326}
327
328fn attention_item(event: &DevelopmentEvent) -> Option<AttentionItem> {
329 let (state, title, detail) = match event.kind {
330 DevelopmentEventKind::ProcessStarted => (
331 AttentionState::Running,
332 "Process running",
333 payload_label(&event.payload, "name", "managed process"),
334 ),
335 DevelopmentEventKind::TestStarted => (
336 AttentionState::Running,
337 "Tests running",
338 payload_label(&event.payload, "name", "test run"),
339 ),
340 DevelopmentEventKind::AgentPrompt => (
341 AttentionState::Running,
342 "Agent working",
343 "bounded local prompt accepted".into(),
344 ),
345 DevelopmentEventKind::DiagnosticsPublished
346 if event
347 .payload
348 .get("count")
349 .and_then(serde_json::Value::as_u64)
350 .unwrap_or(0)
351 > 0 =>
352 {
353 (
354 AttentionState::NeedsAttention,
355 "Diagnostics need attention",
356 payload_label(&event.payload, "path", "project diagnostics"),
357 )
358 }
359 DevelopmentEventKind::SemanticBreakpointHit => (
360 AttentionState::NeedsAttention,
361 "Semantic breakpoint hit",
362 payload_label(&event.payload, "entity", "browser entity changed"),
363 ),
364 DevelopmentEventKind::ProcessExited => {
365 let failed = event_failed(&event.payload);
366 (
367 if failed {
368 AttentionState::NeedsAttention
369 } else {
370 AttentionState::Recent
371 },
372 if failed {
373 "Process failed"
374 } else {
375 "Process completed"
376 },
377 payload_label(&event.payload, "name", "managed process"),
378 )
379 }
380 DevelopmentEventKind::TestCompleted => {
381 let failed = event_failed(&event.payload);
382 (
383 if failed {
384 AttentionState::NeedsAttention
385 } else {
386 AttentionState::Recent
387 },
388 if failed {
389 "Tests failed"
390 } else {
391 "Tests passed"
392 },
393 payload_label(&event.payload, "name", "test run"),
394 )
395 }
396 DevelopmentEventKind::VerificationCompleted => (
397 AttentionState::Recent,
398 "Verification completed",
399 payload_label(&event.payload, "status", "verification evidence updated"),
400 ),
401 DevelopmentEventKind::FileSaved => (
402 AttentionState::Recent,
403 "File saved",
404 payload_label(&event.payload, "path", "project file"),
405 ),
406 _ => return None,
407 };
408 Some(AttentionItem {
409 id: format!("attention:{}", event.id),
410 state,
411 title: title.into(),
412 detail,
413 occurred_at_ms: event.occurred_at_ms,
414 event_id: event.id.clone(),
415 })
416}
417
418fn event_failed(payload: &serde_json::Value) -> bool {
419 if payload.get("success").and_then(serde_json::Value::as_bool) == Some(false)
420 || payload
421 .get("code")
422 .and_then(serde_json::Value::as_i64)
423 .is_some_and(|code| code != 0)
424 || payload
425 .get("status")
426 .and_then(serde_json::Value::as_str)
427 .is_some_and(|status| matches!(status, "failed" | "timeout" | "cancelled"))
428 {
429 return true;
430 }
431 let Some(state) = payload.get("state") else {
432 return false;
433 };
434 state.as_str() == Some("failed")
435 || state
436 .get("exited")
437 .and_then(|exited| exited.get("code"))
438 .and_then(serde_json::Value::as_i64)
439 .is_some_and(|code| code != 0)
440}
441
442fn payload_label(payload: &serde_json::Value, field: &str, fallback: &str) -> String {
443 payload
444 .get(field)
445 .and_then(serde_json::Value::as_str)
446 .filter(|value| value.len() <= 256)
447 .unwrap_or(fallback)
448 .to_string()
449}
450
451#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
452#[serde(rename_all = "camelCase")]
453pub struct VerificationCheck {
454 pub label: String,
455 pub status: String,
456 pub detail: String,
457}
458
459#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
460#[serde(rename_all = "camelCase")]
461pub struct VerificationCard {
462 pub schema_version: String,
463 pub title: String,
464 pub outcome: String,
465 pub checks: Vec<VerificationCheck>,
466 pub changed_files: usize,
467 pub semantic_revision: Option<u64>,
468 pub visual_status: String,
469 pub generated_at_ms: u64,
470}
471
472impl VerificationCard {
473 pub fn from_diff(
474 title: &str,
475 diff: &ProjectDiff,
476 semantic_revision: Option<u64>,
477 ) -> DevelopmentResult<Self> {
478 if title.trim().is_empty() || title.len() > 128 {
479 return Err(DevelopmentError::InvalidInput(
480 "verification card title must be 1-128 bytes".into(),
481 ));
482 }
483 let visual_status = diff
484 .visual
485 .get("status")
486 .and_then(serde_json::Value::as_str)
487 .unwrap_or("not-captured")
488 .to_string();
489 let process_count = diff
490 .runtime
491 .get("processCount")
492 .and_then(serde_json::Value::as_u64)
493 .unwrap_or(0);
494 let link_count = diff
495 .semantic
496 .get("linkCount")
497 .and_then(serde_json::Value::as_u64)
498 .unwrap_or(0);
499 Ok(Self {
500 schema_version: DEVELOPMENT_SCHEMA_VERSION.into(),
501 title: title.into(),
502 outcome: "reviewRequired".into(),
503 checks: vec![
504 VerificationCheck {
505 label: "Code changes".into(),
506 status: if diff.files.is_empty() {
507 "clean"
508 } else {
509 "changed"
510 }
511 .into(),
512 detail: format!("{} changed files", diff.files.len()),
513 },
514 VerificationCheck {
515 label: "Runtime".into(),
516 status: "observed".into(),
517 detail: format!("{process_count} managed processes"),
518 },
519 VerificationCheck {
520 label: "Semantic links".into(),
521 status: "observed".into(),
522 detail: format!("{link_count} source/runtime links"),
523 },
524 VerificationCheck {
525 label: "Visual evidence".into(),
526 status: visual_status.clone(),
527 detail: if visual_status == "not-captured" {
528 "request an explicit screenshot or comparison".into()
529 } else {
530 "explicit visual evidence attached".into()
531 },
532 },
533 ],
534 changed_files: diff.files.len(),
535 semantic_revision,
536 visual_status,
537 generated_at_ms: now_ms(),
538 })
539 }
540
541 pub fn add_check(&mut self, check: VerificationCheck) -> DevelopmentResult<()> {
542 if self.checks.len() == MAX_VERIFICATION_CHECKS {
543 return Err(DevelopmentError::InvalidInput(
544 "verification card check limit reached".into(),
545 ));
546 }
547 if check.label.is_empty() || check.label.len() > 128 || check.detail.len() > 512 {
548 return Err(DevelopmentError::InvalidInput(
549 "verification check exceeds bounded text limits".into(),
550 ));
551 }
552 self.checks.push(check);
553 Ok(())
554 }
555}
556
557fn now_ms() -> u64 {
558 SystemTime::now()
559 .duration_since(UNIX_EPOCH)
560 .map_or(0, |duration| duration.as_millis() as u64)
561}
562
563#[cfg(test)]
564mod tests {
565 use super::*;
566
567 fn fixture(name: &str) -> PathBuf {
568 let root =
569 std::env::temp_dir().join(format!("glass-cockpit-{name}-{}", std::process::id()));
570 let _ = fs::remove_dir_all(&root);
571 fs::create_dir_all(&root).unwrap();
572 fs::write(
573 root.join("Cargo.toml"),
574 "[package]\nname='demo'\nversion='0.1.0'\n",
575 )
576 .unwrap();
577 root
578 }
579
580 #[test]
581 fn resident_registry_reuses_and_evicts_bounded_workspaces() {
582 let first = fixture("first");
583 let second = fixture("second");
584 let mut sessions = ResidentDevelopmentSessions::new(1, Duration::from_secs(60));
585 sessions
586 .with_workspace(&first, |workspace| {
587 workspace.attach_actor(super::super::Actor::external("one"))?;
588 Ok(())
589 })
590 .unwrap();
591 sessions
592 .with_workspace(&first, |workspace| {
593 assert!(workspace.actors().any(|actor| actor.id == "external:one"));
594 Ok(())
595 })
596 .unwrap();
597 sessions.with_workspace(&second, |_| Ok(())).unwrap();
598 assert_eq!(sessions.len(), 1);
599 assert!(!sessions.contains(&first));
600 assert!(sessions.contains(&second));
601 let _ = fs::remove_dir_all(first);
602 let _ = fs::remove_dir_all(second);
603 }
604
605 #[test]
606 fn reconnect_capsule_round_trips_without_payload_fields() {
607 let root = fixture("capsule");
608 let mut capsule = ReconnectCapsule::new(&root).unwrap();
609 capsule.event_cursor = Some("dev-1".into());
610 capsule.mobile_view = Some("app".into());
611 capsule.mobile_scroll = Some(20);
612 ReconnectCapsuleStore::save(&capsule).unwrap();
613 assert_eq!(ReconnectCapsuleStore::load(&root).unwrap(), Some(capsule));
614 assert!(ReconnectCapsuleStore::clear(&root).unwrap());
615 assert_eq!(ReconnectCapsuleStore::load(&root).unwrap(), None);
616 let _ = fs::remove_dir_all(root);
617 }
618
619 #[test]
620 fn reconnect_capsule_accepts_current_and_legacy_mobile_views() {
621 let root = fixture("capsule-mobile-views");
622 for view in [
623 "home", "overview", "agent", "app", "browser", "diff", "project", "process", "logs",
624 ] {
625 let mut capsule = ReconnectCapsule::new(&root).unwrap();
626 capsule.mobile_view = Some(view.into());
627 capsule.validate().unwrap();
628 }
629 let mut capsule = ReconnectCapsule::new(&root).unwrap();
630 capsule.mobile_view = Some("unknown".into());
631 assert!(capsule.validate().is_err());
632 let _ = fs::remove_dir_all(root);
633 }
634
635 #[test]
636 fn resident_registry_expires_idle_state_before_reopening() {
637 let root = fixture("expiry");
638 fs::write(root.join("src.rs"), "fn main() {}\n").unwrap();
639 let mut sessions = ResidentDevelopmentSessions::new(2, Duration::ZERO);
640 sessions
641 .with_workspace(&root, |workspace| {
642 workspace.open_buffer("src.rs", super::super::Actor::local())?;
643 Ok(())
644 })
645 .unwrap();
646 let retained = sessions
647 .with_workspace(&root, |workspace| Ok(workspace.buffer("src.rs").is_some()))
648 .unwrap();
649 assert!(!retained);
650 let _ = fs::remove_dir_all(root);
651 }
652
653 #[test]
654 fn attention_inbox_classifies_only_actionable_runtime_events() {
655 let events = vec![
656 DevelopmentEvent::new(
657 super::super::Actor::local(),
658 DevelopmentEventKind::WorkspaceOpened,
659 "/tmp",
660 serde_json::json!({}),
661 1,
662 ),
663 DevelopmentEvent::new(
664 super::super::Actor::local(),
665 DevelopmentEventKind::DiagnosticsPublished,
666 "/tmp",
667 serde_json::json!({"count":2,"path":"src/lib.rs"}),
668 2,
669 ),
670 DevelopmentEvent::new(
671 super::super::Actor::local(),
672 DevelopmentEventKind::ProcessStarted,
673 "/tmp",
674 serde_json::json!({"name":"dev"}),
675 3,
676 ),
677 DevelopmentEvent::new(
678 super::super::Actor::local(),
679 DevelopmentEventKind::TestCompleted,
680 "/tmp",
681 serde_json::json!({"name":"unit","state":{"exited":{"code":1}}}),
682 4,
683 ),
684 ];
685 let inbox = attention_inbox(events.into_iter());
686 assert_eq!(inbox.len(), 3);
687 assert!(
688 inbox
689 .iter()
690 .any(|item| item.state == AttentionState::Running)
691 );
692 assert!(inbox.iter().any(|item| item.title == "Tests failed"));
693 }
694
695 #[test]
696 fn verification_card_keeps_visual_evidence_explicit() {
697 let diff = ProjectDiff {
698 schema_version: DEVELOPMENT_SCHEMA_VERSION.into(),
699 files: vec![],
700 runtime: BTreeMap::from([("processCount".into(), serde_json::json!(1))]),
701 semantic: BTreeMap::from([("linkCount".into(), serde_json::json!(2))]),
702 visual: BTreeMap::from([("status".into(), serde_json::json!("not-captured"))]),
703 workflow: BTreeMap::new(),
704 test_impact: BTreeMap::new(),
705 };
706 let card = VerificationCard::from_diff("Checkout fix", &diff, Some(9)).unwrap();
707 assert_eq!(card.visual_status, "not-captured");
708 assert_eq!(card.checks.len(), 4);
709 assert!(card.checks[3].detail.contains("explicit screenshot"));
710 }
711}