studio-worker 0.4.6

Pull-based image-generation worker for the minis.gg studio.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! Config tab — user-editable subset of [`Config`] reachable as
//! widgets.  Save writes through `crate::config::save`; the runtime
//! loops pick up the new values on their next tick because every
//! tick snapshots `Arc<Mutex<Config>>`.
//!
//! Internal state (`worker_id`, `auth_token`, `install_id`,
//! `registration_*`) is deliberately not surfaced here.  The
//! auto-register flow owns it end-to-end.

use std::path::{Path, PathBuf};

use eframe::egui;

use crate::config::{self, default_models_root, Config};

use super::super::notifier::NotificationPrefs;
use crate::autostart;

/// Buffer the user is editing.  `dirty` is true when any field
/// differs from `original`; Save / Reset clear it.
#[derive(Debug, Clone)]
pub struct ConfigDraft {
    pub current: Config,
    pub original: Config,
    pub last_save_error: Option<String>,
    /// Last autostart-toggle failure, surfaced next to the toggle so
    /// the operator sees why it did not stick (the checkbox otherwise
    /// silently reverts on the next frame because `is_enabled()`
    /// re-reads disk).
    pub autostart_error: Option<String>,
}

impl ConfigDraft {
    pub fn from(cfg: &Config) -> Self {
        Self {
            current: cfg.clone(),
            original: cfg.clone(),
            last_save_error: None,
            autostart_error: None,
        }
    }

    pub fn dirty(&self) -> bool {
        !configs_equal(&self.current, &self.original)
    }

    pub fn save(&mut self, path: &Path) -> Result<(), String> {
        match config::save(&self.current, path) {
            Ok(()) => {
                // An operator deliberately applying settings through the
                // window is a discrete, rare action that warrants an
                // info-level breadcrumb — unlike `config::save`, which
                // the auto-register poll loop calls every tick and so
                // logs the routine persist at debug.  Emitting here (not
                // in `config::save`) keeps that hot path quiet while
                // surfacing operator-driven changes in default logs.
                // Only non-secret, user-editable fields are named.
                let changed = changed_fields(&self.original, &self.current).join(",");
                tracing::info!(
                    target: "studio_worker::ui::config",
                    changed = ?changed,
                    vram_threshold_gb = self.current.vram_threshold_gb,
                    auto_start = self.current.auto_start,
                    auto_update_enabled = self.current.auto_update_enabled,
                    models_root = %self.current.models_root.display(),
                    "operator applied config changes via UI"
                );
                self.original = self.current.clone();
                self.last_save_error = None;
                Ok(())
            }
            Err(e) => {
                let msg = format!("{e}");
                self.last_save_error = Some(msg.clone());
                Err(msg)
            }
        }
    }

    pub fn reset(&mut self) {
        self.current = self.original.clone();
        self.last_save_error = None;
        self.autostart_error = None;
    }
}

/// Equality over the persisted, user-editable fields.  Internal state
/// (registration ids, auth token, worker id, install id) is excluded
/// because the UI never mutates it; the auto-register flow owns it.
///
/// Delegates to [`changed_fields`] so the dirty-check and the save
/// breadcrumb can never drift: any field that dirties the form is, by
/// construction, also named when the operator applies it.
fn configs_equal(a: &Config, b: &Config) -> bool {
    changed_fields(a, b).is_empty()
}

/// Names of the user-editable fields that differ between `a` and `b`,
/// in declaration order.  Backs both the dirty-check ([`configs_equal`])
/// and the operator-apply breadcrumb in [`ConfigDraft::save`], so the
/// two share a single source of truth for "what the UI can change".
fn changed_fields(a: &Config, b: &Config) -> Vec<&'static str> {
    let mut fields = Vec::new();
    if a.api_base_url != b.api_base_url {
        fields.push("api_base_url");
    }
    if (a.vram_threshold_gb - b.vram_threshold_gb).abs() >= f32::EPSILON {
        fields.push("vram_threshold_gb");
    }
    if a.auto_start != b.auto_start {
        fields.push("auto_start");
    }
    if a.start_minimised != b.start_minimised {
        fields.push("start_minimised");
    }
    if a.auto_update_enabled != b.auto_update_enabled {
        fields.push("auto_update_enabled");
    }
    if a.auto_update_interval_secs != b.auto_update_interval_secs {
        fields.push("auto_update_interval_secs");
    }
    if a.auto_update_feed != b.auto_update_feed {
        fields.push("auto_update_feed");
    }
    if a.auto_update_prerelease != b.auto_update_prerelease {
        fields.push("auto_update_prerelease");
    }
    if a.models_root != b.models_root {
        fields.push("models_root");
    }
    fields
}

pub fn render(
    ui: &mut egui::Ui,
    draft: &mut ConfigDraft,
    config_path: &Path,
    notification_prefs: &mut NotificationPrefs,
) -> bool {
    let mut saved = false;
    ui.heading("Configuration");
    ui.label(
        egui::RichText::new(format!("{}", config_path.display()))
            .color(egui::Color32::from_gray(150))
            .small(),
    );
    ui.add_space(8.0);

    section(ui, "Connection", |ui| {
        labeled_text(ui, "API base URL", &mut draft.current.api_base_url);
    });

    section(ui, "Worker", |ui| {
        labeled_slider(
            ui,
            "VRAM threshold (GB)",
            &mut draft.current.vram_threshold_gb,
            0.0,
            96.0,
        );
        labeled_bool(ui, "Auto-start on boot", &mut draft.current.auto_start);
    });

    section(ui, "Auto-update", |ui| {
        labeled_bool(
            ui,
            "Auto-update enabled",
            &mut draft.current.auto_update_enabled,
        );
        labeled_u64(
            ui,
            "Interval (seconds)",
            &mut draft.current.auto_update_interval_secs,
        );
        labeled_text(ui, "Release feed URL", &mut draft.current.auto_update_feed);
        labeled_bool(
            ui,
            "Track pre-releases",
            &mut draft.current.auto_update_prerelease,
        );
    });

    section(ui, "Models", |ui| {
        labeled_folder(ui, "Models root", &mut draft.current.models_root);
        ui.label("");
        ui.label(
            egui::RichText::new(
                "This is where the models will be stored.  You might need a fair bit \
                 of disk space to be able to satisfy different types of jobs.",
            )
            .italics()
            .color(egui::Color32::from_gray(160)),
        );
        ui.end_row();
    });

    section(ui, "Notifications", |ui| {
        ui.label("On job completion");
        ui.checkbox(&mut notification_prefs.on_completion, "");
        ui.end_row();
        ui.label("On job failure");
        ui.checkbox(&mut notification_prefs.on_failure, "");
        ui.end_row();
    });

    let mut autostart_enabled = autostart::is_enabled();
    let prev_autostart = autostart_enabled;
    section(ui, "Background mode", |ui| {
        ui.label("Run in tray on login");
        ui.checkbox(&mut autostart_enabled, "");
        ui.end_row();
        ui.label("Start minimised");
        ui.checkbox(&mut draft.current.start_minimised, "");
        ui.end_row();
    });
    if autostart_enabled != prev_autostart {
        let outcome = match std::env::current_exe() {
            Ok(exe) if autostart_enabled => autostart::enable(&exe),
            Ok(_) => autostart::disable(),
            Err(e) => Err(anyhow::anyhow!("cannot resolve current executable: {e}")),
        };
        // `autostart::enable`/`disable` already emit a structured
        // tracing event; surface any failure in the UI too so the
        // operator sees why the toggle did not stick instead of it
        // silently reverting on the next frame.
        draft.autostart_error = outcome.err().map(|e| format!("{e}"));
    }
    if let Some(err) = &draft.autostart_error {
        ui.colored_label(
            egui::Color32::LIGHT_RED,
            format!("could not change autostart: {err}"),
        );
    }

    ui.add_space(12.0);
    ui.horizontal(|ui| {
        let dirty = draft.dirty();
        let save = ui.add_enabled(dirty, egui::Button::new("Save"));
        if save.clicked() {
            saved = draft.save(config_path).is_ok();
        }
        if ui.add_enabled(dirty, egui::Button::new("Reset")).clicked() {
            draft.reset();
        }
        if let Some(err) = &draft.last_save_error {
            ui.colored_label(egui::Color32::LIGHT_RED, format!("save failed: {err}"));
        } else if !dirty && draft.last_save_error.is_none() {
            ui.label(
                egui::RichText::new("up to date")
                    .italics()
                    .color(egui::Color32::from_gray(150)),
            );
        }
    });
    saved
}

// ---------------------------------------------------------------------------
// Widget helpers
// ---------------------------------------------------------------------------

fn section(ui: &mut egui::Ui, title: &str, add: impl FnOnce(&mut egui::Ui)) {
    egui::CollapsingHeader::new(title)
        .default_open(true)
        .show(ui, |ui| {
            egui::Grid::new(title)
                .num_columns(2)
                .spacing([12.0, 6.0])
                .show(ui, |ui| {
                    add(ui);
                });
        });
    ui.add_space(4.0);
}

fn labeled_text(ui: &mut egui::Ui, label: &str, value: &mut String) {
    ui.label(label);
    ui.add(egui::TextEdit::singleline(value).desired_width(360.0));
    ui.end_row();
}

fn labeled_bool(ui: &mut egui::Ui, label: &str, value: &mut bool) {
    ui.label(label);
    ui.checkbox(value, "");
    ui.end_row();
}

fn labeled_slider(ui: &mut egui::Ui, label: &str, value: &mut f32, min: f32, max: f32) {
    ui.label(label);
    ui.add(egui::Slider::new(value, min..=max).fixed_decimals(1));
    ui.end_row();
}

fn labeled_u64(ui: &mut egui::Ui, label: &str, value: &mut u64) {
    ui.label(label);
    let mut buf = value.to_string();
    if ui
        .add(egui::TextEdit::singleline(&mut buf).desired_width(120.0))
        .changed()
    {
        if let Ok(n) = buf.parse::<u64>() {
            *value = n;
        }
    }
    ui.end_row();
}

/// Path-with-folder-picker widget.  The text edit reflects the
/// current value at all times; the "Browse…" button opens the
/// native picker (rfd) and overwrites it on confirm.
fn labeled_folder(ui: &mut egui::Ui, label: &str, value: &mut PathBuf) {
    ui.label(label);
    ui.horizontal(|ui| {
        let mut buf = value.to_string_lossy().to_string();
        let r = ui.add(egui::TextEdit::singleline(&mut buf).desired_width(280.0));
        if r.changed() {
            *value = PathBuf::from(buf);
        }
        if ui.button("Browse…").clicked() {
            let starting = if value.is_absolute() {
                value.clone()
            } else {
                default_models_root()
            };
            if let Some(picked) = rfd::FileDialog::new()
                .set_directory(starting.parent().unwrap_or(&starting))
                .pick_folder()
            {
                *value = picked;
            }
        }
    });
    ui.end_row();
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn draft_starts_clean() {
        let cfg = Config::default();
        let draft = ConfigDraft::from(&cfg);
        assert!(!draft.dirty());
    }

    #[test]
    fn draft_marks_dirty_after_edit() {
        let cfg = Config::default();
        let mut draft = ConfigDraft::from(&cfg);
        draft.current.vram_threshold_gb = 24.0;
        assert!(draft.dirty());
    }

    #[test]
    fn draft_marks_dirty_when_models_root_changes() {
        let cfg = Config::default();
        let mut draft = ConfigDraft::from(&cfg);
        draft.current.models_root = PathBuf::from("/tmp/other-models");
        assert!(draft.dirty());
    }

    #[test]
    fn save_writes_through_and_clears_dirty() {
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let cfg = Config::default();
        let mut draft = ConfigDraft::from(&cfg);
        draft.current.vram_threshold_gb = 24.0;
        draft.save(&path).unwrap();
        assert!(!draft.dirty());
        // Reload from disk and confirm the value persisted.
        let (loaded, _) = config::load(Some(&path.to_string_lossy())).unwrap();
        assert!((loaded.vram_threshold_gb - 24.0).abs() < f32::EPSILON);
    }

    #[test]
    fn reset_reverts_unsaved_edits() {
        let cfg = Config::default();
        let mut draft = ConfigDraft::from(&cfg);
        draft.current.vram_threshold_gb = 33.0;
        draft.reset();
        assert!((draft.current.vram_threshold_gb - cfg.vram_threshold_gb).abs() < f32::EPSILON);
        assert!(!draft.dirty());
    }

    #[test]
    fn reset_clears_autostart_error() {
        let cfg = Config::default();
        let mut draft = ConfigDraft::from(&cfg);
        draft.autostart_error = Some("boom".into());
        draft.reset();
        assert!(draft.autostart_error.is_none());
    }

    #[test]
    fn changed_fields_names_only_differing_user_editable_fields() {
        let base = Config::default();
        let mut edited = base.clone();
        edited.vram_threshold_gb = base.vram_threshold_gb + 8.0;
        edited.models_root = PathBuf::from("/tmp/other-models");
        let changed = changed_fields(&base, &edited);
        assert_eq!(changed, vec!["vram_threshold_gb", "models_root"]);
    }

    #[test]
    fn changed_fields_is_empty_for_identical_configs() {
        let cfg = Config::default();
        assert!(changed_fields(&cfg, &cfg).is_empty());
    }

    #[test]
    fn save_emits_operator_apply_breadcrumb() {
        use crate::test_support::capture;
        let dir = tempdir().unwrap();
        let path = dir.path().join("config.toml");
        let logs = capture(move || {
            let cfg = Config::default();
            let mut draft = ConfigDraft::from(&cfg);
            draft.current.vram_threshold_gb = 24.0;
            draft.save(&path).expect("save must succeed");
        });
        assert!(logs.contains("INFO"), "expected INFO level, got: {logs}");
        assert!(
            logs.contains("studio_worker::ui::config"),
            "expected ui::config target, got: {logs}"
        );
        assert!(
            logs.contains("changed=\"vram_threshold_gb\""),
            "expected the changed field list, got: {logs}"
        );
        assert!(
            logs.contains("operator applied config changes via UI"),
            "expected the apply message, got: {logs}"
        );
    }

    #[test]
    fn save_failure_records_last_save_error() {
        let cfg = Config::default();
        let mut draft = ConfigDraft::from(&cfg);
        // /proc is read-only on Linux — a write attempt fails.
        let bad = Path::new("/proc/this-should-fail/config.toml");
        let res = draft.save(bad);
        assert!(res.is_err());
        assert!(draft.last_save_error.is_some());
    }
}