1use serde::{Deserialize, Serialize};
8use std::fs;
9use std::path::{Path, PathBuf};
10
11use crate::state::{app_meta_dir, config_file_path};
12
13pub const SETUP_STATE_VERSION: u32 = 5;
14
15pub const REQUIRED_SETUP_STEPS: [&str; 8] = [
19 "welcome",
20 "storage",
21 "control",
22 "device",
23 "inference",
24 "relations", "care",
26 "ready",
27];
28
29pub const PROGRESSIVE_SETUP_PATHS: [&str; 6] = [
32 "reachability", "assurance", "people_connections", "domains_mail", "care_records", "peer_agreements", ];
39
40#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
46pub struct DeviceContext {
47 #[serde(default)]
50 pub ownership: String,
51 #[serde(default)]
53 pub machine_fleet: String,
54 #[serde(default)]
56 pub user_scope: String,
57 #[serde(default)]
60 pub shared_setting: String,
61 #[serde(default)]
63 pub notes: String,
64}
65
66#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
67pub struct SetupProfile {
68 #[serde(default)]
69 pub preferred_name: String,
70 #[serde(default)]
71 pub locale: String,
72 #[serde(default)]
73 pub timezone: String,
74 #[serde(default)]
75 pub accessibility_needs: Vec<String>,
76 #[serde(default)]
77 pub interests: Vec<String>,
78 #[serde(default)]
79 pub preferred_ontologies: Vec<String>,
80 #[serde(default)]
81 pub care_priorities: Vec<String>,
82 #[serde(default)]
83 pub qapp_goals: Vec<String>,
84 #[serde(default)]
86 pub device_context: DeviceContext,
87}
88
89#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
90pub struct SetupState {
91 pub version: u32,
92 #[serde(default)]
93 pub completed: bool,
94 #[serde(default = "default_current_step")]
95 pub current_step: String,
96 #[serde(default)]
97 pub completed_steps: Vec<String>,
98 #[serde(default)]
99 pub migrated_from_legacy_config: bool,
100 #[serde(default)]
101 pub profile: SetupProfile,
102}
103
104fn default_current_step() -> String {
105 "welcome".to_string()
106}
107
108impl Default for SetupState {
109 fn default() -> Self {
110 Self {
111 version: SETUP_STATE_VERSION,
112 completed: false,
113 current_step: default_current_step(),
114 completed_steps: Vec::new(),
115 migrated_from_legacy_config: false,
116 profile: SetupProfile::default(),
117 }
118 }
119}
120
121pub fn update_setup_profile(profile: SetupProfile) -> Result<SetupState, String> {
123 let mut state = get_setup_state()?;
124 state.profile = profile;
125 save_setup_state_to(&setup_state_path(), &state)?;
126 let _ = crate::identity_plane::sync_local_device_context(&state.profile.device_context);
128 Ok(state)
129}
130
131pub fn setup_state_path() -> PathBuf {
133 app_meta_dir().join("setup-state.json")
134}
135
136pub fn get_setup_state() -> Result<SetupState, String> {
138 load_setup_state_from(&setup_state_path(), config_file_path().exists())
139}
140
141pub fn complete_setup_step(step: String) -> Result<SetupState, String> {
143 let step = step.trim();
144 let is_required = REQUIRED_SETUP_STEPS.contains(&step);
145 let is_progressive = PROGRESSIVE_SETUP_PATHS.contains(&step);
146 if !is_required && !is_progressive {
147 return Err(format!("Unknown setup step: {step}"));
148 }
149
150 let mut state = get_setup_state()?;
151 if state.completed && is_required {
153 return Ok(state);
154 }
155 if !state.completed_steps.iter().any(|done| done == step) {
156 state.completed_steps.push(step.to_string());
157 }
158 if !state.completed {
159 state.current_step = next_incomplete_step(&state).unwrap_or("ready").to_string();
160 }
161 save_setup_state_to(&setup_state_path(), &state)?;
162 Ok(state)
163}
164
165pub fn finish_setup() -> Result<SetupState, String> {
167 let mut state = get_setup_state()?;
168 let missing: Vec<&str> = REQUIRED_SETUP_STEPS
169 .iter()
170 .copied()
171 .filter(|required| {
172 !state
173 .completed_steps
174 .iter()
175 .any(|completed| completed == required)
176 })
177 .collect();
178 if !missing.is_empty() {
179 return Err(format!(
180 "Complete the required setup steps first: {}",
181 missing.join(", ")
182 ));
183 }
184
185 state.completed = true;
186 state.current_step = "complete".to_string();
187 save_setup_state_to(&setup_state_path(), &state)?;
188 crate::identity_plane::ensure_local_apparatus(Some(state.profile.device_context.clone()))?;
191 Ok(state)
192}
193
194fn next_incomplete_step(state: &SetupState) -> Option<&'static str> {
195 REQUIRED_SETUP_STEPS.iter().copied().find(|required| {
196 !state
197 .completed_steps
198 .iter()
199 .any(|completed| completed == required)
200 })
201}
202
203fn load_setup_state_from(path: &Path, legacy_config_exists: bool) -> Result<SetupState, String> {
204 match fs::read_to_string(path) {
205 Ok(text) => {
206 let mut state: SetupState = serde_json::from_str(&text)
207 .map_err(|error| format!("Could not read setup state: {error}"))?;
208 state.version = SETUP_STATE_VERSION;
209 Ok(state)
210 }
211 Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
212 if legacy_config_exists {
213 let state = SetupState {
214 completed: true,
215 current_step: "complete".to_string(),
216 completed_steps: REQUIRED_SETUP_STEPS
217 .iter()
218 .map(|step| (*step).to_string())
219 .collect(),
220 migrated_from_legacy_config: true,
221 ..SetupState::default()
222 };
223 save_setup_state_to(path, &state)?;
224 Ok(state)
225 } else {
226 Ok(SetupState::default())
227 }
228 }
229 Err(error) => Err(format!("Could not read setup state: {error}")),
230 }
231}
232
233fn save_setup_state_to(path: &Path, state: &SetupState) -> Result<(), String> {
234 if let Some(parent) = path.parent() {
235 fs::create_dir_all(parent)
236 .map_err(|error| format!("Could not create setup directory: {error}"))?;
237 }
238 let json = serde_json::to_string_pretty(state)
239 .map_err(|error| format!("Could not encode setup state: {error}"))?;
240 fs::write(path, json).map_err(|error| format!("Could not save setup state: {error}"))
241}
242
243#[cfg(test)]
244mod tests {
245 use super::*;
246
247 #[test]
248 fn new_install_starts_at_welcome() {
249 let dir = tempfile::tempdir().unwrap();
250 let state = load_setup_state_from(&dir.path().join("setup.json"), false).unwrap();
251 assert!(!state.completed);
252 assert_eq!(state.current_step, "welcome");
253 assert!(state.completed_steps.is_empty());
254 }
255
256 #[test]
257 fn legacy_config_is_migrated_without_showing_the_gate() {
258 let dir = tempfile::tempdir().unwrap();
259 let path = dir.path().join("setup.json");
260 let state = load_setup_state_from(&path, true).unwrap();
261 assert!(state.completed);
262 assert!(state.migrated_from_legacy_config);
263 assert!(path.exists());
264 }
265
266 #[test]
267 fn required_step_order_is_deterministic() {
268 let mut state = SetupState::default();
269 assert_eq!(next_incomplete_step(&state), Some("welcome"));
270 state.completed_steps.push("welcome".into());
271 assert_eq!(next_incomplete_step(&state), Some("storage"));
272 state.completed_steps.push("storage".into());
273 for step in REQUIRED_SETUP_STEPS.iter().skip(2) {
274 state.completed_steps.push((*step).into());
275 }
276 assert_eq!(next_incomplete_step(&state), None);
277 }
278
279 #[test]
280 fn first_run_gate_does_not_require_relational_paths() {
281 assert!(!REQUIRED_SETUP_STEPS.contains(&"reachability"));
282 assert!(!REQUIRED_SETUP_STEPS.contains(&"assurance"));
283 assert!(PROGRESSIVE_SETUP_PATHS.contains(&"reachability"));
284 assert!(PROGRESSIVE_SETUP_PATHS.contains(&"people_connections"));
285 assert_eq!(REQUIRED_SETUP_STEPS.len(), 8);
286 }
287
288 #[test]
289 fn older_setup_state_gets_an_empty_profile() {
290 let state: SetupState = serde_json::from_str(
291 r#"{"version":2,"completed":false,"current_step":"care","completed_steps":[]}"#,
292 )
293 .unwrap();
294 assert_eq!(state.profile, SetupProfile::default());
295 assert_eq!(state.profile.device_context, DeviceContext::default());
296 }
297
298 #[test]
299 fn device_context_deserializes_on_v5_profile() {
300 let state: SetupState = serde_json::from_str(
301 r#"{
302 "version":5,
303 "completed":false,
304 "current_step":"device",
305 "completed_steps":[],
306 "profile":{
307 "device_context":{
308 "ownership":"owned_by_me",
309 "machine_fleet":"one_of_several",
310 "user_scope":"more_than_one",
311 "shared_setting":"family",
312 "notes":""
313 }
314 }
315 }"#,
316 )
317 .unwrap();
318 assert_eq!(state.profile.device_context.ownership, "owned_by_me");
319 assert_eq!(state.profile.device_context.shared_setting, "family");
320 }
321}