agentmux_srv_core/migrations/
m0045_palette_snap.rs1use std::sync::Arc;
25
26use crate::backend::browser_profiles_store::{profiles_file_path, read_profiles, write_profiles, BrowserProfile};
27use crate::backend::palette::snap_hex;
28use crate::backend::storage::store::{AgentContent, Store};
29use crate::registry::{resolve_shared_definitions_dir, DefinitionStore};
30
31use super::{Migration, MigrationContext, MigrationError, MigrationScope};
32
33pub struct M0045PaletteSnap;
34
35pub(super) fn snapped(stored: &str) -> Option<String> {
37 let stored = stored.trim();
38 let slot = snap_hex(stored)?;
39 (!slot.hex.eq_ignore_ascii_case(stored)).then(|| slot.hex.clone())
40}
41
42pub(super) fn snap_profiles(profiles: &mut [BrowserProfile]) -> bool {
44 let mut changed = false;
45 for p in profiles {
46 if let Some(hex) = snapped(&p.color) {
47 p.color = hex;
48 changed = true;
49 }
50 }
51 changed
52}
53
54impl Migration for M0045PaletteSnap {
55 fn id(&self) -> &'static str {
56 "0045_palette_snap"
57 }
58 fn scope(&self) -> MigrationScope {
59 MigrationScope::Channel
60 }
61 fn description(&self) -> &'static str {
62 "Snap agent and browser profile colours to the shared palette's nearest slot"
63 }
64
65 fn up(&self, ctx: &MigrationContext) -> Result<(), MigrationError> {
66 if ctx.channel_store_path.exists() {
67 snap_agent_colors(&ctx.channel_store_path)?;
68 }
69 if let Some(path) = profiles_file_path() {
70 if let Err(e) = snap_profiles_file(&path) {
72 tracing::warn!(error = %e, "palette_snap: leaving browser profiles as they are");
73 }
74 }
75 Ok(())
76 }
77}
78
79pub(super) fn snap_profiles_file(path: &std::path::Path) -> Result<(), String> {
80 let mut profiles = read_profiles(path).map_err(|e| format!("read profiles: {e}"))?;
81 if snap_profiles(&mut profiles) {
82 write_profiles(path, &profiles).map_err(|e| format!("write profiles: {e}"))?;
83 }
84 Ok(())
85}
86
87pub(super) fn snap_agent_colors(store_path: &std::path::Path) -> Result<(), MigrationError> {
88 let mstore = Arc::new(
89 Store::open(store_path).map_err(|e| MigrationError(format!("palette_snap: open mstore: {e}")))?,
90 );
91 if let Some(def_dir) = resolve_shared_definitions_dir() {
93 match DefinitionStore::open(def_dir) {
94 Ok(def_store) => mstore.set_def_registry(Arc::new(def_store)),
95 Err(e) => tracing::warn!(error = %e, "palette_snap: failed to open global def registry, snapping local-only"),
96 }
97 }
98 let defs = mstore
99 .agent_def_list()
100 .map_err(|e| MigrationError(format!("palette_snap: list defs: {e}")))?;
101 let now = std::time::SystemTime::now()
102 .duration_since(std::time::UNIX_EPOCH)
103 .map(|d| d.as_millis() as i64)
104 .unwrap_or(0);
105 for def in defs {
106 let Some(existing) = mstore
107 .agent_content_get(&def.id, "ui:color")
108 .map_err(|e| MigrationError(format!("palette_snap: get {}: {e}", def.id)))?
109 else {
110 continue;
111 };
112 let Some(hex) = snapped(&existing.content) else { continue };
113 mstore
114 .agent_content_set(&AgentContent {
115 agent_id: def.id.clone(),
116 content_type: "ui:color".to_string(),
117 content: hex,
118 updated_at: now,
119 })
120 .map_err(|e| MigrationError(format!("palette_snap: set {}: {e}", def.id)))?;
121 }
122 Ok(())
123}
124
125#[cfg(test)]
126pub(in crate::migrations) mod tests {
127 use super::*;
128 use crate::backend::palette::slots;
129 use crate::backend::storage::agents::AgentDefinition;
130 use crate::test_support::ISOLATED_AUTH_ENV_LOCK as ENV_GUARD;
131
132 pub(in crate::migrations) fn with_isolated_home<T>(f: impl FnOnce() -> T) -> T {
135 let _guard = ENV_GUARD.lock().unwrap_or_else(|e| e.into_inner());
136 let home_tmp = tempfile::tempdir().unwrap();
137 std::env::set_var("AGENTMUX_HOME_OVERRIDE", home_tmp.path().to_str().unwrap());
138 let result = f();
139 std::env::remove_var("AGENTMUX_HOME_OVERRIDE");
140 result
141 }
142
143 pub(in crate::migrations) fn ctx_for(path: &std::path::Path) -> MigrationContext {
144 MigrationContext {
145 home: std::env::temp_dir(),
146 data_dir: std::env::temp_dir(),
147 shared_store_path: std::env::temp_dir().join("unused-store.db"),
148 channel_store_path: path.to_path_buf(),
149 }
150 }
151
152 pub(in crate::migrations) fn insert_def(mstore: &Store, name: &str) -> String {
153 let mut def = AgentDefinition {
154 seat: None,
155 conversation_visibility: crate::backend::storage::agents::default_conversation_visibility(),
156 id: format!("test-{name}"),
157 slug: String::new(),
158 name: name.to_string(),
159 icon: String::new(),
160 provider: "claude".to_string(),
161 description: String::new(),
162 working_directory: String::new(),
163 shell: String::new(),
164 provider_flags: String::new(),
165 auto_start: 0,
166 restart_on_crash: 0,
167 idle_timeout_minutes: 0,
168 created_at: 1,
169 agent_type: "host".to_string(),
170 environment: String::new(),
171 agent_bus_id: String::new(),
172 is_seeded: 0,
173 accounts: String::new(),
174 parent_id: String::new(),
175 branch_label: String::new(),
176 updated_at: 1,
177 user_hidden: 0,
178 container_image: String::new(),
179 container_volumes: "[]".to_string(),
180 container_name: String::new(),
181 use_ambient_login: 0,
182 model_vendor_base_url: String::new(),
183 memory_id: String::new(),
184 };
185 mstore.agent_def_insert(&mut def).unwrap();
186 def.id
187 }
188
189 pub(in crate::migrations) fn set_color(mstore: &Store, id: &str, color: &str, at: i64) {
190 mstore
191 .agent_content_set(&AgentContent {
192 agent_id: id.to_string(),
193 content_type: "ui:color".to_string(),
194 content: color.to_string(),
195 updated_at: at,
196 })
197 .unwrap();
198 }
199
200 #[test]
201 fn an_old_colour_snaps_and_a_slot_hex_or_junk_is_left_alone() {
202 assert_eq!(snapped("#14b8a6").as_deref(), Some("#00b5b3"));
203 assert_eq!(snapped(" #14B8A6 ").as_deref(), Some("#00b5b3"));
204 assert_eq!(snapped(&slots()[3].hex), None);
205 assert_eq!(snapped(&slots()[3].hex.to_uppercase()), None);
206 assert_eq!(snapped("junk"), None);
207 assert_eq!(snapped(""), None);
208 }
209
210 #[test]
211 fn profiles_snap_and_report_whether_anything_changed() {
212 let profile = |color: &str| BrowserProfile {
213 id: "p-1".into(),
214 name: "Work".into(),
215 color: color.into(),
216 created_at: 0,
217 agents_allowed: false,
218 owner_agent: None,
219 };
220 let mut ps = vec![profile("#ec4899"), profile(&slots()[0].hex)];
221 assert!(snap_profiles(&mut ps));
222 assert_eq!(ps[0].color, "#e47696");
223 assert_eq!(ps[1].color, slots()[0].hex);
224 assert!(!snap_profiles(&mut ps), "a second run changes nothing");
225 }
226
227 #[test]
228 fn agent_colours_snap_once_and_an_agent_without_one_stays_without() {
229 with_isolated_home(|| {
230 let tmp = tempfile::NamedTempFile::new().unwrap();
231 let mstore = Store::open(tmp.path()).unwrap();
232 let old = insert_def(&mstore, "old");
233 let current = insert_def(&mstore, "current");
234 let none = insert_def(&mstore, "none");
235 set_color(&mstore, &old, "#3b82f6", 7);
236 set_color(&mstore, ¤t, &slots()[5].hex, 42);
237
238 M0045PaletteSnap.up(&ctx_for(tmp.path())).unwrap();
239
240 let snapped_old = mstore.agent_content_get(&old, "ui:color").unwrap().unwrap();
241 assert_eq!(snapped_old.content, "#61a0f4", "Tailwind blue is Blue");
242 let kept = mstore.agent_content_get(¤t, "ui:color").unwrap().unwrap();
243 assert_eq!((kept.content.as_str(), kept.updated_at), (slots()[5].hex.as_str(), 42));
244 assert!(mstore.agent_content_get(&none, "ui:color").unwrap().is_none());
245
246 M0045PaletteSnap.up(&ctx_for(tmp.path())).unwrap();
247 let again = mstore.agent_content_get(&old, "ui:color").unwrap().unwrap();
248 assert_eq!(again.updated_at, snapped_old.updated_at, "idempotent");
249 });
250 }
251
252 #[test]
253 fn a_corrupt_profiles_file_is_reported_not_fatal() {
254 let tmp = tempfile::tempdir().unwrap();
255 let path = tmp.path().join("browser-profiles.json");
256 std::fs::write(&path, "{ not json").unwrap();
257 assert!(snap_profiles_file(&path).is_err());
258 assert_eq!(std::fs::read_to_string(&path).unwrap(), "{ not json", "left untouched");
259 }
260
261 #[test]
262 fn a_missing_channel_store_is_a_noop() {
263 with_isolated_home(|| {
264 M0045PaletteSnap.up(&ctx_for(std::path::Path::new("Z:/does/not/exist/objects.db"))).unwrap();
265 });
266 }
267}