1use std::io::{BufRead, Write};
13use std::net::{IpAddr, Ipv4Addr, SocketAddr};
14use std::time::Duration;
15
16use anyhow::Context;
17use clap::{Args, ValueEnum};
18use serde::{Deserialize, Serialize};
19
20use crate::cli::admin::{
21 ADMIN_SERVE_START_DEADLINE, FOREGROUND_SERVE_NOTICE, ServerSessionDescriptor,
22 operator_server_reachable, start_operator_server,
23};
24use crate::cli::browser::{BrowserOpener, OsBrowserOpener};
25use crate::cli::harness::{AttachEntry, HarnessId, HarnessRegistry, HarnessState};
26use crate::cli::harness_apply::{self, ApplyOutcome, PlannedAction};
27use crate::cli::operator_profile::{AuthPosture, OperatorSetupProfile};
28use crate::server::serve::DEFAULT_LISTEN;
29
30#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum, Serialize, Deserialize)]
38pub enum InstallationType {
39 #[value(name = "in-harness")]
41 #[serde(rename = "in-harness")]
42 InHarness,
43 #[serde(rename = "server")]
45 Server,
46 #[serde(rename = "both")]
48 Both,
49}
50
51#[derive(Args, Debug, Clone)]
53pub struct SetupCliArgs {
54 #[arg(long)]
57 pub non_interactive: bool,
58
59 #[arg(long, value_enum)]
61 pub installation_type: Option<InstallationType>,
62
63 #[arg(long)]
65 pub port: Option<u16>,
66
67 #[arg(long, value_delimiter = ',')]
69 pub harnesses: Vec<String>,
70
71 #[arg(long)]
73 pub yes: bool,
74}
75
76pub trait SetupSink {
82 fn status(&mut self, line: &str);
84 fn ask_choice(&mut self, q: &str, opts: &[&str]) -> usize;
86 fn confirm(&mut self, action_plan: &str) -> bool;
88}
89
90pub struct StderrSetupSink;
97
98impl SetupSink for StderrSetupSink {
99 fn status(&mut self, line: &str) {
100 eprintln!("{line}");
101 }
102
103 fn ask_choice(&mut self, q: &str, opts: &[&str]) -> usize {
104 eprintln!("{q}");
105 for (i, opt) in opts.iter().enumerate() {
106 eprintln!(" {}) {opt}", i + 1);
107 }
108 eprint!("> ");
109 let _ = std::io::stderr().flush();
110 let line = read_stdin_line();
111 match line.trim().parse::<usize>() {
112 Ok(n) if (1..=opts.len()).contains(&n) => n - 1,
113 _ => 0,
116 }
117 }
118
119 fn confirm(&mut self, action_plan: &str) -> bool {
120 eprintln!("{action_plan}");
121 eprint!("Proceed? [y/N] ");
122 let _ = std::io::stderr().flush();
123 let line = read_stdin_line();
124 matches!(line.trim().to_ascii_lowercase().as_str(), "y" | "yes")
125 }
126}
127
128fn read_stdin_line() -> String {
131 let mut line = String::new();
132 let stdin = std::io::stdin();
133 let _ = stdin.lock().read_line(&mut line);
134 line
135}
136
137#[derive(Debug, Default)]
141pub struct ScriptedSetupSink {
142 choices: std::collections::VecDeque<usize>,
144 confirm_answer: bool,
146 pub statuses: Vec<String>,
148 pub questions: Vec<String>,
150 pub confirmations: Vec<String>,
152}
153
154impl ScriptedSetupSink {
155 pub fn new(choices: impl IntoIterator<Item = usize>, confirm_answer: bool) -> Self {
157 Self {
158 choices: choices.into_iter().collect(),
159 confirm_answer,
160 statuses: Vec::new(),
161 questions: Vec::new(),
162 confirmations: Vec::new(),
163 }
164 }
165}
166
167impl SetupSink for ScriptedSetupSink {
168 fn status(&mut self, line: &str) {
169 self.statuses.push(line.to_string());
170 }
171
172 fn ask_choice(&mut self, q: &str, opts: &[&str]) -> usize {
173 self.questions.push(format!("{q} [{}]", opts.join(", ")));
174 self.choices.pop_front().unwrap_or(0)
177 }
178
179 fn confirm(&mut self, action_plan: &str) -> bool {
180 self.confirmations.push(action_plan.to_string());
181 self.confirm_answer
182 }
183}
184
185#[derive(Debug, Clone)]
187pub struct SetupContext {
188 pub home: std::path::PathBuf,
189 pub working_dir: std::path::PathBuf,
190}
191
192impl SetupContext {
193 pub fn from_env() -> anyhow::Result<Self> {
195 let home = dirs::home_dir().context("cannot determine home directory")?;
196 let working_dir =
197 std::env::current_dir().context("cannot determine current working directory")?;
198 Ok(Self { home, working_dir })
199 }
200
201 pub fn project_base(&self) -> std::path::PathBuf {
203 self.working_dir.clone()
204 }
205
206 pub fn registry(&self) -> HarnessRegistry {
210 HarnessRegistry::known_with(&self.home, &self.working_dir)
211 }
212}
213
214#[derive(Debug)]
221pub struct WizardOutcome {
222 pub installation_type: InstallationType,
224 pub session: Option<ServerSessionDescriptor>,
227 pub reused_server: bool,
230 pub harness_outcomes: Vec<ApplyOutcome>,
232 pub browser_outcome: Option<crate::cli::browser::BrowserOpenOutcome>,
234 pub profile: OperatorSetupProfile,
237 pub cancelled: bool,
239}
240
241pub fn run(args: SetupCliArgs) -> anyhow::Result<()> {
245 let ctx = SetupContext::from_env()?;
246 if args.non_interactive {
247 let mut sink = ScriptedSetupSink::new([], args.yes);
250 let browser = crate::cli::browser::NoopBrowserOpener::default();
251 run_wizard(args, &ctx, &mut sink, &browser)?;
252 } else {
253 let mut sink = StderrSetupSink;
254 let browser = OsBrowserOpener;
255 let outcome = run_wizard(args, &ctx, &mut sink, &browser)?;
256 serve_foreground_if_wizard_started(&outcome, block_until_ctrl_c)?;
268 }
269 Ok(())
270}
271
272fn serve_foreground_if_wizard_started(
287 outcome: &WizardOutcome,
288 wait_for_shutdown: impl FnOnce(&ServerSessionDescriptor) -> anyhow::Result<()>,
289) -> anyhow::Result<()> {
290 if outcome.reused_server {
291 return Ok(());
292 }
293 let Some(session) = outcome.session.as_ref() else {
294 return Ok(());
295 };
296 eprintln!("{FOREGROUND_SERVE_NOTICE}");
297 wait_for_shutdown(session)
298}
299
300fn block_until_ctrl_c(_session: &ServerSessionDescriptor) -> anyhow::Result<()> {
308 let runtime = tokio::runtime::Builder::new_current_thread()
309 .enable_all()
310 .build()?;
311 runtime.block_on(tokio::signal::ctrl_c())?;
312 Ok(())
313}
314
315pub fn run_wizard<S: SetupSink + ?Sized, B: BrowserOpener + ?Sized>(
323 args: SetupCliArgs,
324 ctx: &SetupContext,
325 sink: &mut S,
326 browser: &B,
327) -> anyhow::Result<WizardOutcome> {
328 let placement = crate::paths::process_control_state_placement();
329 run_wizard_with_control_state(args, ctx, sink, browser, placement.directory(), None)
330}
331
332#[doc(hidden)]
333pub fn run_wizard_with_control_state<S: SetupSink + ?Sized, B: BrowserOpener + ?Sized>(
334 args: SetupCliArgs,
335 ctx: &SetupContext,
336 sink: &mut S,
337 browser: &B,
338 control_state_dir: Option<&crate::domain::ControlStateDir>,
339 workspace_root: Option<&std::path::Path>,
342) -> anyhow::Result<WizardOutcome> {
343 let registry = ctx.registry();
344 let existing_profile = control_state_dir.and_then(OperatorSetupProfile::load);
345
346 let suggested_port = suggest_free_port(args.port)?;
348 sink.status(&format!(
349 "SymForge setup — OS: {} — suggested port: {suggested_port}",
350 std::env::consts::OS
351 ));
352 for status in scan_harness_summary(®istry, None) {
353 sink.status(&status);
354 }
355
356 let remembered = existing_profile.as_ref().map(|p| p.port);
358 let mut remembered_reachable: Option<SocketAddr> = None;
359 if let Some(port) = remembered {
360 let addr = loopback_addr(port);
361 if operator_server_reachable(addr, Duration::from_millis(500)) {
362 remembered_reachable = Some(addr);
363 sink.status(&format!(
364 "Operator server already reachable on {addr} (profile port {port}) — will reuse"
365 ));
366 }
367 }
368
369 let installation_type = resolve_installation_type(&args, sink)?;
371 let selected_ids = resolve_harness_ids(&args, ®istry);
372 let bind_port = args.port.unwrap_or(suggested_port);
373 let bind_addr = loopback_addr(bind_port);
374
375 let needs_server = matches!(
376 installation_type,
377 InstallationType::Server | InstallationType::Both
378 );
379 let needs_harness_http = installation_type == InstallationType::Both;
380
381 let action_plan = build_action_plan(
387 installation_type,
388 &selected_ids,
389 bind_addr,
390 needs_server,
391 needs_harness_http,
392 );
393 if !args.yes && !sink.confirm(&action_plan) {
394 sink.status("Setup cancelled — no changes made.");
395 let profile = OperatorSetupProfile::new(
396 installation_type,
397 bind_port,
398 AuthPosture::LoopbackNoKey,
399 &selected_ids,
400 now_epoch_ms(),
401 );
402 return Ok(WizardOutcome {
403 installation_type,
404 session: None,
405 reused_server: false,
406 harness_outcomes: Vec::new(),
407 browser_outcome: None,
408 profile,
409 cancelled: true,
410 });
411 }
412 if args.yes {
413 sink.status(&action_plan);
415 }
416
417 if installation_type == InstallationType::InHarness {
418 sink.status(
419 "In-harness (stdio) mode: configure local MCP clients with `symforge init` per client.",
420 );
421 }
422
423 let mut session: Option<ServerSessionDescriptor> = None;
425 let mut reused_server = false;
426 if needs_server {
427 if let Some(addr) = remembered_reachable {
428 session = Some(ServerSessionDescriptor::for_addr(addr, true));
430 reused_server = true;
431 sink.status(&format!("Reusing running operator server on {addr}"));
432 }
433 if session.is_none() {
434 sink.status(&format!("Starting operator server on {bind_addr}…"));
435 session = Some(start_operator_server(
448 Some(bind_addr),
449 args.port.is_some(),
450 None,
451 None,
452 ADMIN_SERVE_START_DEADLINE,
453 workspace_root.map(std::path::Path::to_path_buf),
454 )?);
455 }
456 let desc = session.as_ref().expect("session started or reused");
457 sink.status(&format!("Dashboard: {}", desc.dashboard_url));
458 sink.status(&format!("Attach: {}", desc.attach_url));
459 }
460
461 let mut harness_outcomes = Vec::new();
463 if needs_harness_http {
464 let desc = session
465 .as_ref()
466 .context("internal error: harness HTTP attach requires a running operator server")?;
467 let attach_entry = AttachEntry::new(desc.attach_url.clone(), None);
468 let subset = registry_subset(®istry, &selected_ids);
469 let plan = harness_apply::plan(&subset, &attach_entry);
470 sink.status("Applying harness attach entries (restorable backups)…");
471 for change in &plan.changes {
472 let label = match &change.action {
473 PlannedAction::Add => "add",
474 PlannedAction::Refresh => "refresh",
475 PlannedAction::Skip(reason) => {
476 sink.status(&format!(" [skip] {} ({reason})", change.id.display_name()));
477 continue;
478 }
479 PlannedAction::Error(reason) => {
480 sink.status(&format!(
481 " [error] {} ({reason})",
482 change.id.display_name()
483 ));
484 continue;
485 }
486 };
487 sink.status(&format!(
488 " [{label}] {} -> {}",
489 change.id.display_name(),
490 change.config_path.display()
491 ));
492 }
493 harness_outcomes = harness_apply::apply(&plan);
494 for outcome in &harness_outcomes {
495 match outcome {
496 ApplyOutcome::Wrote {
497 id,
498 config_path,
499 backup,
500 } => {
501 let backup_note = backup
502 .as_ref()
503 .map(|b| format!(" (backup: {})", b.backup.display()))
504 .unwrap_or_default();
505 sink.status(&format!(
506 " [written] {} -> {}{backup_note}",
507 id.display_name(),
508 config_path.display()
509 ));
510 }
511 ApplyOutcome::Skipped { id, reason } => {
512 sink.status(&format!(" [skipped] {} ({reason})", id.display_name()));
513 }
514 ApplyOutcome::Failed { id, reason } => {
515 sink.status(&format!(" [failed] {} ({reason})", id.display_name()));
516 }
517 }
518 }
519 }
520
521 let bound_port = session
523 .as_ref()
524 .map(|s| s.bound_addr.port())
525 .unwrap_or(bind_port);
526 let profile = OperatorSetupProfile::new(
527 installation_type,
528 bound_port,
529 AuthPosture::LoopbackNoKey,
530 &selected_ids,
531 now_epoch_ms(),
532 );
533 profile
534 .save(control_state_dir.context("process control state unavailable")?)
535 .context("could not persist operator setup profile")?;
536
537 let mut browser_outcome = None;
539 if let Some(desc) = &session {
540 let outcome = browser.open_url(&desc.dashboard_url);
541 sink.status(&format!(
542 "Browser: {outcome:?} — open {}",
543 desc.dashboard_url
544 ));
545 browser_outcome = Some(outcome);
546 }
547
548 sink.status("Setup complete.");
549 Ok(WizardOutcome {
550 installation_type,
551 session,
552 reused_server,
553 harness_outcomes,
554 browser_outcome,
555 profile,
556 cancelled: false,
557 })
558}
559
560fn now_epoch_ms() -> i64 {
561 std::time::SystemTime::now()
562 .duration_since(std::time::UNIX_EPOCH)
563 .unwrap_or_default()
564 .as_millis() as i64
565}
566
567fn loopback_addr(port: u16) -> SocketAddr {
568 SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), port)
569}
570
571fn suggest_free_port(preferred: Option<u16>) -> anyhow::Result<u16> {
572 let preferred_addr = preferred
573 .map(loopback_addr)
574 .or_else(|| DEFAULT_LISTEN.parse().ok());
575 let addr = crate::cli::admin::select_free_addr_std(preferred_addr)
576 .map_err(|e| anyhow::anyhow!("could not find a free operator-server port: {e}"))?;
577 Ok(addr.port())
578}
579
580fn scan_harness_summary(registry: &HarnessRegistry, attach: Option<&AttachEntry>) -> Vec<String> {
581 let entry = attach
582 .cloned()
583 .unwrap_or_else(|| AttachEntry::new("", None));
584 registry
585 .scan(&entry)
586 .into_iter()
587 .map(|s| {
588 format!(
589 " {} — {} ({})",
590 s.id.display_name(),
591 format_harness_state(&s.state),
592 s.config_path.display()
593 )
594 })
595 .collect()
596}
597
598fn format_harness_state(state: &HarnessState) -> &'static str {
599 match state {
600 HarnessState::NotInstalled => "not installed",
601 HarnessState::Absent => "not configured",
602 HarnessState::PresentCurrent => "configured (current)",
603 HarnessState::PresentStale => "configured (stale)",
604 HarnessState::Malformed(_) => "unreadable",
605 }
606}
607
608fn resolve_installation_type<S: SetupSink + ?Sized>(
609 args: &SetupCliArgs,
610 sink: &mut S,
611) -> anyhow::Result<InstallationType> {
612 if let Some(t) = args.installation_type {
613 return Ok(t);
614 }
615 if args.non_interactive {
616 return Ok(InstallationType::Both);
617 }
618 let idx = sink.ask_choice(
619 "Installation type?",
620 &[
621 "in-harness only (stdio via symforge init)",
622 "operator server + dashboard",
623 "both (server + harness HTTP attach)",
624 ],
625 );
626 Ok(match idx {
627 0 => InstallationType::InHarness,
628 1 => InstallationType::Server,
629 _ => InstallationType::Both,
630 })
631}
632
633fn resolve_harness_ids(args: &SetupCliArgs, registry: &HarnessRegistry) -> Vec<HarnessId> {
634 if !args.harnesses.is_empty() {
635 return args
636 .harnesses
637 .iter()
638 .filter_map(|slug| harness_id_from_slug(slug))
639 .collect();
640 }
641 let entry = AttachEntry::new("", None);
642 registry
643 .scan(&entry)
644 .into_iter()
645 .filter(|s| !matches!(s.state, HarnessState::NotInstalled))
646 .map(|s| s.id)
647 .collect()
648}
649
650fn harness_id_from_slug(slug: &str) -> Option<HarnessId> {
651 let slug = slug.trim().to_ascii_lowercase();
652 [
653 HarnessId::ClaudeCode,
654 HarnessId::ClaudeDesktop,
655 HarnessId::Codex,
656 HarnessId::Gemini,
657 HarnessId::KiloCode,
658 HarnessId::Cursor,
659 ]
660 .into_iter()
661 .find(|id| id.slug() == slug)
662}
663
664fn registry_subset(registry: &HarnessRegistry, ids: &[HarnessId]) -> HarnessRegistry {
665 let targets = registry
666 .targets()
667 .iter()
668 .filter(|t| ids.contains(&t.id))
669 .cloned()
670 .collect();
671 HarnessRegistry::from_targets(targets)
672}
673
674fn build_action_plan(
675 installation_type: InstallationType,
676 harnesses: &[HarnessId],
677 bind_addr: SocketAddr,
678 needs_server: bool,
679 needs_harness_http: bool,
680) -> String {
681 let mut lines = vec![format!(
682 "Planned actions ({}):",
683 installation_type_label(installation_type)
684 )];
685 if needs_server {
686 lines.push(format!(" • start operator server on {bind_addr}"));
687 }
688 if needs_harness_http {
689 for id in harnesses {
690 lines.push(format!(
691 " • configure {} HTTP attach (backup + write)",
692 id.display_name()
693 ));
694 }
695 }
696 if installation_type == InstallationType::InHarness {
697 lines.push(" • no server; use `symforge init` for stdio MCP clients".to_string());
698 }
699 lines.join("\n")
700}
701
702fn installation_type_label(t: InstallationType) -> &'static str {
703 match t {
704 InstallationType::InHarness => "in-harness",
705 InstallationType::Server => "server",
706 InstallationType::Both => "both",
707 }
708}
709
710#[cfg(test)]
711mod tests {
712 use super::*;
713
714 fn control_over(home: &std::path::Path) -> crate::domain::ControlStateDir {
715 crate::domain::ControlStateDir::new(home.join("control"))
716 }
717
718 #[test]
719 fn scripted_sink_returns_scripted_answers_and_records_prompts() {
720 let mut sink = ScriptedSetupSink::new([1, 0], true);
721
722 sink.status("scanning harnesses");
723 let first = sink.ask_choice("install type?", &["in-harness", "server", "both"]);
724 let second = sink.ask_choice("which harness?", &["claude", "codex"]);
725 let proceed = sink.confirm("will configure: claude");
726
727 assert_eq!(first, 1, "first ask_choice pops the first scripted answer");
729 assert_eq!(second, 0, "second ask_choice pops the next scripted answer");
730 assert!(proceed, "confirm returns the scripted bool");
731
732 assert_eq!(sink.statuses, vec!["scanning harnesses"]);
734 assert_eq!(sink.questions.len(), 2);
735 assert!(sink.questions[0].contains("install type?"));
736 assert!(sink.questions[0].contains("in-harness, server, both"));
737 assert_eq!(sink.confirmations, vec!["will configure: claude"]);
738 }
739
740 #[test]
741 fn scripted_sink_defaults_to_first_when_script_exhausted() {
742 let mut sink = ScriptedSetupSink::new([], false);
744 assert_eq!(sink.ask_choice("pick", &["a", "b"]), 0);
745 assert!(!sink.confirm("plan"));
746 }
747
748 #[test]
749 fn installation_type_serde_uses_contract_strings() {
750 assert_eq!(
753 serde_json::to_string(&InstallationType::InHarness).unwrap(),
754 "\"in-harness\""
755 );
756 assert_eq!(
757 serde_json::to_string(&InstallationType::Both).unwrap(),
758 "\"both\""
759 );
760 let parsed: InstallationType = serde_json::from_str("\"server\"").unwrap();
761 assert_eq!(parsed, InstallationType::Server);
762 }
763
764 #[test]
765 fn non_interactive_setup_configures_fixture_and_persists_profile() {
766 use crate::cli::admin::operator_server_reachable;
767 use crate::cli::browser::NoopBrowserOpener;
768 use crate::cli::harness::{HarnessFormat, HarnessTarget, SYMFORGE_SERVER_NAME};
769 use crate::cli::harness_apply::{PlannedAction, plan};
770
771 let home = tempfile::tempdir().expect("temp home");
772 let project = tempfile::tempdir().expect("temp project");
773 let control = control_over(home.path());
774 let cfg = home.path().join(".claude.json");
775 std::fs::write(&cfg, "{}\n").expect("fixture harness config");
776
777 let ctx = SetupContext {
778 home: home.path().to_path_buf(),
779 working_dir: project.path().to_path_buf(),
780 };
781
782 let mut sink = ScriptedSetupSink::new([], true);
783 let browser = NoopBrowserOpener::default();
784
785 let outcome = run_wizard_with_control_state(
786 SetupCliArgs {
787 non_interactive: true,
788 installation_type: Some(InstallationType::Both),
789 port: None,
790 harnesses: vec!["claude".into()],
791 yes: true,
792 },
793 &ctx,
794 &mut sink,
795 &browser,
796 Some(&control),
797 Some(project.path()),
798 )
799 .expect("setup should succeed");
800
801 assert!(!outcome.cancelled);
802 assert_eq!(outcome.installation_type, InstallationType::Both);
803
804 assert!(
805 sink.statuses.iter().any(|l| l.contains("Claude Code")),
806 "scan must list harnesses: {:?}",
807 sink.statuses
808 );
809
810 let profile = OperatorSetupProfile::load(&control).expect("profile persisted");
811 assert_eq!(profile.installation_type, InstallationType::Both);
812 assert!(profile.port > 0);
813 assert_eq!(profile.harnesses, vec!["claude"]);
814
815 let after = std::fs::read_to_string(&cfg).expect("config exists");
816 assert!(after.contains(SYMFORGE_SERVER_NAME));
817
818 let session = outcome.session.as_ref().expect("server started");
820 assert!(session.reachable);
821 let attach_url = session.attach_url.clone();
822 assert!(attach_url.contains("/mcp"));
823
824 assert!(
825 operator_server_reachable(session.bound_addr, Duration::from_millis(500)),
826 "server must be reachable on reported port"
827 );
828 assert_eq!(browser.opened_urls().len(), 1);
829
830 let entry = AttachEntry::new(attach_url, None);
831 let reg = HarnessRegistry::from_targets(vec![HarnessTarget {
832 id: HarnessId::ClaudeCode,
833 config_path: cfg,
834 format: HarnessFormat::Json,
835 }]);
836 let p2 = plan(®, &entry);
837 assert!(matches!(p2.changes[0].action, PlannedAction::Skip(_)));
838 }
839
840 #[test]
841 fn non_interactive_decline_writes_nothing_and_is_not_an_error() {
842 use crate::cli::browser::NoopBrowserOpener;
843
844 let home = tempfile::tempdir().expect("temp home");
845 let project = tempfile::tempdir().expect("temp project");
846 let control = control_over(home.path());
847 let cfg = home.path().join(".claude.json");
848 let original = "{\n \"mcpServers\": {}\n}\n";
849 std::fs::write(&cfg, original).expect("fixture");
850
851 let ctx = SetupContext {
852 home: home.path().to_path_buf(),
853 working_dir: project.path().to_path_buf(),
854 };
855 let mut sink = ScriptedSetupSink::new([], false);
857 let browser = NoopBrowserOpener::default();
858
859 let outcome = run_wizard_with_control_state(
860 SetupCliArgs {
861 non_interactive: true,
862 installation_type: Some(InstallationType::Both),
863 port: None,
864 harnesses: vec!["claude".into()],
865 yes: false,
866 },
867 &ctx,
868 &mut sink,
869 &browser,
870 Some(&control),
871 Some(project.path()),
872 )
873 .expect("a decline is a clean no-op, not an error");
874
875 assert!(outcome.cancelled);
877 assert!(outcome.session.is_none());
878 assert!(outcome.harness_outcomes.is_empty());
879 assert_eq!(std::fs::read_to_string(&cfg).unwrap(), original);
880 assert!(OperatorSetupProfile::load(&control).is_none());
881 assert_eq!(sink.confirmations.len(), 1);
883 }
884
885 #[test]
886 fn setup_holds_foreground_after_fresh_start_until_shutdown() {
887 use crate::cli::admin::operator_server_reachable;
894 use crate::cli::browser::NoopBrowserOpener;
895
896 let home = tempfile::tempdir().expect("temp home");
897 let project = tempfile::tempdir().expect("temp project");
898 let control = control_over(home.path());
899 let ctx = SetupContext {
900 home: home.path().to_path_buf(),
901 working_dir: project.path().to_path_buf(),
902 };
903 let mut sink = ScriptedSetupSink::new([], true);
904 let browser = NoopBrowserOpener::default();
905
906 let outcome = run_wizard_with_control_state(
907 SetupCliArgs {
908 non_interactive: true,
909 installation_type: Some(InstallationType::Server),
910 port: None,
911 harnesses: vec![],
912 yes: true,
913 },
914 &ctx,
915 &mut sink,
916 &browser,
917 Some(&control),
918 Some(project.path()),
919 )
920 .expect("server-mode setup should start a server when none runs");
921 assert!(
922 !outcome.reused_server,
923 "no server ran; the wizard must start one"
924 );
925 assert!(
926 outcome.session.is_some(),
927 "a fresh start yields a live session"
928 );
929
930 let waited = std::cell::Cell::new(false);
931 serve_foreground_if_wizard_started(&outcome, |session| {
932 waited.set(true);
933 assert!(
936 operator_server_reachable(session.bound_addr, Duration::from_millis(500)),
937 "freshly-started server must be reachable while setup holds the foreground"
938 );
939 std::thread::sleep(Duration::from_millis(300));
940 assert!(
941 operator_server_reachable(session.bound_addr, Duration::from_millis(500)),
942 "the started server must STAY reachable (D21: it must not die after start)"
943 );
944 Ok(())
945 })
946 .expect("foreground wait returns cleanly on shutdown");
947
948 assert!(
949 waited.get(),
950 "a freshly-started server must hold the foreground (D21 fix); pre-fix `run` returned immediately"
951 );
952 assert!(
956 FOREGROUND_SERVE_NOTICE.contains("Ctrl-C"),
957 "the foreground notice must tell the operator how to stop it"
958 );
959 }
960
961 #[test]
962 fn setup_does_not_hold_foreground_when_reusing() {
963 use crate::cli::browser::NoopBrowserOpener;
967
968 let preferred = SocketAddr::new(IpAddr::V4(Ipv4Addr::LOCALHOST), 0);
969 let workspace = tempfile::tempdir().expect("temp workspace");
970 let running = start_operator_server(
971 Some(preferred),
972 false,
973 None,
974 None,
975 ADMIN_SERVE_START_DEADLINE,
976 Some(workspace.path().to_path_buf()),
977 )
978 .expect("operator server should come up");
979
980 let home = tempfile::tempdir().expect("temp home");
981 let project = tempfile::tempdir().expect("temp project");
982 let control = control_over(home.path());
983 OperatorSetupProfile::new(
984 InstallationType::Server,
985 running.bound_addr.port(),
986 AuthPosture::LoopbackNoKey,
987 &[],
988 1,
989 )
990 .save(&control)
991 .expect("persist profile");
992
993 let ctx = SetupContext {
994 home: home.path().to_path_buf(),
995 working_dir: project.path().to_path_buf(),
996 };
997 let mut sink = ScriptedSetupSink::new([], true);
998 let browser = NoopBrowserOpener::default();
999
1000 let outcome = run_wizard_with_control_state(
1001 SetupCliArgs {
1002 non_interactive: true,
1003 installation_type: Some(InstallationType::Server),
1004 port: None,
1005 harnesses: vec![],
1006 yes: true,
1007 },
1008 &ctx,
1009 &mut sink,
1010 &browser,
1011 Some(&control),
1012 Some(project.path()),
1013 )
1014 .expect("server-mode setup should reuse the running server");
1015 assert!(
1016 outcome.reused_server,
1017 "must reuse the already-running server"
1018 );
1019
1020 let waited = std::cell::Cell::new(false);
1021 serve_foreground_if_wizard_started(&outcome, |_| {
1022 waited.set(true);
1023 Ok(())
1024 })
1025 .expect("reuse path returns cleanly");
1026 assert!(
1027 !waited.get(),
1028 "the reuse path must not hold the foreground (another process owns the server)"
1029 );
1030 }
1031}