返回 CodeWhale
startup_defaults.rs
根目录 / crates / tui / src / tui / startup_defaults.rs
1 //! The single owner for mode, reasoning and pet-view defaults written back by interactive
2 //! TUI selectors. Provider/model choices persist through `config_persistence`.
3 //!
4 //! Before this module there were three unrelated writers for the same
5 //! `settings.toml` keys: the model picker's combined model+effort apply, the
6 //! effort-only picker apply, and — for `default_mode` — nothing at all, so
7 //! cycling into Operate reverted to Act on the next launch while the preset
8 //! and `/config` surfaces persisted correctly. Routing every interactive
9 //! selector through [`StartupDefaults`] keeps one load/normalize/save
10 //! transaction per user action and one place where the write can be audited.
11 //!
12 //! Every write goes through one per-`App` owner, [`StartupDefaultsWriter`],
13 //! which is what makes the two application shapes safe to mix:
14 //!
15 //! - [`StartupDefaultsWriter::apply_blocking`] is synchronous. The model picker
16 //! uses it because it must know whether the write landed before it records a
17 //! provider/model setup receipt.
18 //! - [`StartupDefaultsWriter::spawn`] is non-blocking. Mode cycling and
19 //! reasoning cycling are keystroke-rate actions, so they must never gate a
20 //! redraw on disk I/O. Failures are still truthful: they land in a
21 //! [`StartupDefaultFailures`] mailbox that the event loop drains into a
22 //! warning toast, rather than being swallowed.
23 //!
24 //! ## Why the ordering is not left to the scheduler
25 //!
26 //! Each write is a load / modify / save transaction against one
27 //! `settings.toml`. Handing each keystroke its own blocking task lets two of
28 //! those transactions interleave — both load the same bytes, and the one that
29 //! saves last wins regardless of which selection the user made last. That loses
30 //! the newer selection for the same field, and it can also resurrect a stale
31 //! value for a *different* field, because each save writes the whole file.
32 //!
33 //! So ordering comes from the enqueue, never from task scheduling:
34 //!
35 //! 1. Every producer is the TUI event loop thread, which processes user actions
36 //! one at a time. `spawn` pushes onto a FIFO queue *synchronously* on that
37 //! thread, so queue order is exactly user-action order.
38 //! 2. A single `write` mutex is held across a whole drain — pop, load, modify,
39 //! save, repeat — so no two transactions ever overlap, no matter how many
40 //! blocking tasks are in flight. Extra tasks simply find the queue empty.
41 //! 3. `apply_blocking` takes the same mutex and first drains everything queued
42 //! ahead of it, then applies its own update. It cannot be overtaken by a
43 //! later action, because a later action can only be enqueued by the event
44 //! loop thread that is currently blocked inside this call.
45 //!
46 //! Together: last user action wins for a field, and because each transaction
47 //! only sets the fields its own [`StartupDefaults`] carries, disjoint fields
48 //! never clobber each other.
49 //!
50 //! ## Why this writer is not the whole story
51 //!
52 //! The `write` mutex above only serializes transactions *this writer* owns, and
53 //! `settings.toml` has other writers in the same process — most sharply, the
54 //! Shift+Tab permission-posture write on the same event loop. Two writers that
55 //! each do their own load / modify / save can still lose a field to each other,
56 //! and locking `save` would not help because the stale read already happened.
57 //!
58 //! So the atomicity of a single load/modify/save belongs one level down, in
59 //! [`Settings::transact`], which holds a per-settings-path process mutex *and*
60 //! a cross-process advisory lock on an adjacent `settings.toml.lock` across the
61 //! whole cycle — the second one because a user can easily have two Codewhale
62 //! processes open on the same home directory. Every reachable settings writer
63 //! goes through it. What stays here is the part `transact` cannot provide:
64 //! **ordering**. A lock makes concurrent transactions safe but says nothing
65 //! about which one runs first, and for keystroke-rate actions "last user action
66 //! wins" is the behavior users can actually perceive.
67 //!
68 //! ## The no-deadlock contract
69 //!
70 //! `write` is held across disk I/O, so it is the *outermost* lock of every
71 //! transaction. `queue` is only ever taken for a single push or pop and never
72 //! across I/O, so it can never be the lock someone waits behind. That gives one
73 //! rule, and it is the rule this module has to keep true:
74 //!
75 //! > **No thread may block on `write` while holding a lock that a settings
76 //! > transaction needs.** Doing so parks the drainer (which holds `write` and
77 //! > wants that lock) against the waiter (which holds that lock and wants
78 //! > `write`).
79 //!
80 //! In production nothing violates it: a settings transaction takes only its own
81 //! two locks (the settings process mutex and the settings file lock), and
82 //! nothing that holds either ever asks for `write`. Under `cfg(test)` a third
83 //! lock joins the order — settings path
84 //! resolution goes through `test_support::with_test_env_lock`, and a
85 //! sealed-`HOME` test holds that lock for its entire body. So a test thread
86 //! calling [`StartupDefaultsWriter::flush`] or
87 //! [`StartupDefaultsWriter::apply_blocking`] would wait on a background drainer
88 //! that is itself parked on the test's own env lock. That inversion is the
89 //! deadlock this module was first shipped with.
90 //!
91 //! [`StartupDefaultsWriter::spawn`] closes it at the source, in two parts:
92 //!
93 //! 1. The background drain is enrolled in the *spawning test's* env scope
94 //! (`test_support::join_env_scope`), so the drain never blocks on a lock its
95 //! own test holds. The env barrier still applies to genuinely foreign
96 //! readers; it just stops treating this test's own writer thread as one of
97 //! them.
98 //! 2. Permission to write at all is keyed to a specific env-scope generation
99 //! (see `spawn_writes_permitted`), not to a process-global flag. A test
100 //! that is not inside an authorized scope enqueues nothing and spawns
101 //! nothing, so it can never become a thread that holds `write` while parked
102 //! on a *foreign* test's env lock. Outstanding-drain accounting is keyed the
103 //! same way, so a closing gate only ever waits for the drains it authorized.
104 //!
105 //! `lock_write` and `Settings::transact` additionally carry test-only deadlines,
106 //! so if the rule is ever broken again the offending test fails with a
107 //! diagnostic instead of hanging CI.
108 //!
109 //! What this module does *not* own: the effective per-turn policy. Session
110 //! restore and preset application call `App::set_mode` directly, which changes
111 //! the live session only. Only a user-facing selection writes a startup
112 //! default.
113
114 use std::collections::VecDeque;
115 use std::sync::{Arc, Mutex, MutexGuard};
116
117 use codewhale_config::AppMode;
118 use codewhale_runtime::settings::Settings;
119
120 /// One user selection's worth of startup-default writes.
121 ///
122 /// Fields left `None` are untouched on disk, so mode and thinking updates
123 /// preserve each other's settings.
124 #[derive(Debug, Clone, Default, PartialEq, Eq)]
125 pub struct StartupDefaults {
126 /// `settings.default_mode` — the mode a fresh session starts in.
127 mode: Option<&'static str>,
128 /// `settings.reasoning_effort` — normalized for the active route by the
129 /// caller, because only the caller knows the route.
130 reasoning_effort: Option<String>,
131 /// `settings.pet_mode` — the main view a fresh session starts in.
132 pet_mode: Option<bool>,
133 whale_name: Option<String>,
134 whale_color: Option<String>,
135 }
136
137 impl StartupDefaults {
138 /// Persist `mode` as the startup default.
139 ///
140 /// `AppMode::as_setting` already collapses the legacy `Yolo` alias to
141 /// `agent`, which is the mode `App::set_mode` actually installs — so the
142 /// persisted value matches the live session rather than a label the user
143 /// never lands in.
144 #[must_use]
145 pub fn mode(mode: AppMode) -> Self {
146 Self {
147 mode: Some(mode.as_setting()),
148 ..Self::default()
149 }
150 }
151
152 /// Persist a route-normalized reasoning-effort setting.
153 #[must_use]
154 pub fn reasoning_effort(setting: impl Into<String>) -> Self {
155 Self {
156 reasoning_effort: Some(setting.into()),
157 ..Self::default()
158 }
159 }
160
161 /// Persist the selected main view without delaying the event loop.
162 #[must_use]
163 pub fn pet_mode(enabled: bool) -> Self {
164 Self {
165 pet_mode: Some(enabled),
166 ..Self::default()
167 }
168 }
169
170 #[must_use]
171 pub fn whale_name(name: &str) -> Self {
172 Self {
173 whale_name: Some(name.to_owned()),
174 ..Self::default()
175 }
176 }
177
178 #[must_use]
179 pub fn whale_color(color: Option<&str>) -> Self {
180 Self {
181 whale_color: Some(color.unwrap_or_default().to_owned()),
182 ..Self::default()
183 }
184 }
185
186 #[cfg(test)]
187 #[must_use]
188 pub fn with_reasoning_effort(mut self, effort: &str) -> Self {
189 self.reasoning_effort = Some(effort.to_string());
190 self
191 }
192
193 #[must_use]
194 pub fn is_empty(&self) -> bool {
195 self.mode.is_none()
196 && self.reasoning_effort.is_none()
197 && self.pet_mode.is_none()
198 && self.whale_name.is_none()
199 && self.whale_color.is_none()
200 }
201
202 /// Which user-facing settings this update touches, as typed subjects.
203 ///
204 /// Deliberately *not* an English string. This module runs on a blocking
205 /// pool with no access to the user's locale, and a failure it prebuilt in
206 /// English would be untranslatable by the time `App` shows it. Callers get
207 /// the enum and translate at the locale boundary (see
208 /// `App::drain_startup_default_failures`).
209 #[must_use]
210 fn subjects(&self) -> Vec<StartupDefaultSubject> {
211 let mut subjects = Vec::new();
212 if self.mode.is_some() {
213 subjects.push(StartupDefaultSubject::Mode);
214 }
215 if self.reasoning_effort.is_some() {
216 subjects.push(StartupDefaultSubject::Thinking);
217 }
218 if self.pet_mode.is_some() {
219 subjects.push(StartupDefaultSubject::PetMode);
220 }
221 if self.whale_name.is_some() {
222 subjects.push(StartupDefaultSubject::WhaleName);
223 }
224 if self.whale_color.is_some() {
225 subjects.push(StartupDefaultSubject::WhaleColor);
226 }
227 subjects
228 }
229
230 /// Load, update, and save `settings.toml` in one transaction.
231 ///
232 /// Private on purpose: callers go through [`StartupDefaultsWriter`], which
233 /// is what serializes these transactions against each other. Calling this
234 /// directly would reintroduce the interleaving described at the top of the
235 /// module.
236 ///
237 /// Every key goes through `Settings::set`, so the same normalization and
238 /// validation the `/config` surface uses applies here too.
239 fn apply(&self) -> anyhow::Result<()> {
240 if self.is_empty() {
241 return Ok(());
242 }
243 Settings::transact(|settings| {
244 if let Some(mode) = self.mode {
245 settings.set("default_mode", mode)?;
246 }
247 if let Some(effort) = self.reasoning_effort.as_deref() {
248 settings.set("reasoning_effort", effort)?;
249 }
250 if let Some(enabled) = self.pet_mode {
251 settings.set("pet_mode", if enabled { "true" } else { "false" })?;
252 }
253 if let Some(name) = self.whale_name.as_deref() {
254 settings.set("whale_name", name)?;
255 }
256 if let Some(color) = self.whale_color.as_deref() {
257 settings.set("whale_color", color)?;
258 }
259 Ok(())
260 })
261 }
262
263 fn apply_reporting(&self, failures: &StartupDefaultFailures) {
264 if let Err(err) = self.apply() {
265 let subjects = self.subjects();
266 // The log line may carry the full chain — it goes to the user's own
267 // log file, not to the screen.
268 tracing::warn!(
269 target: "settings",
270 subjects = ?subjects,
271 error = ?err,
272 "startup default was not persisted"
273 );
274 failures.record(StartupDefaultFailure {
275 subjects,
276 detail: safe_error_detail(&err),
277 });
278 }
279 }
280 }
281
282 /// What a failed startup-default write was trying to save.
283 ///
284 /// `App` maps each variant to a `MessageId`, so the same failure reads in the
285 /// user's language rather than in whatever language the writer thread happened
286 /// to be compiled with.
287 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
288 pub enum StartupDefaultSubject {
289 /// `settings.default_mode`.
290 Mode,
291 /// `settings.reasoning_effort`.
292 Thinking,
293 /// `settings.pet_mode`.
294 PetMode,
295 WhaleName,
296 WhaleColor,
297 }
298
299 /// One startup-default write that did not land.
300 ///
301 /// Typed subjects plus a **short, path-free** error detail. Nothing here is UI
302 /// copy: the sentence around it is assembled by `App` from a `MessageId`.
303 #[derive(Debug, Clone, PartialEq, Eq)]
304 pub struct StartupDefaultFailure {
305 /// Empty only for the unreachable "empty update failed" case.
306 pub subjects: Vec<StartupDefaultSubject>,
307 /// Cause, safe to render: the root cause's own message with any path-like
308 /// token replaced. See [`safe_error_detail`].
309 pub detail: String,
310 }
311
312 /// Reduce an error chain to one short line that is safe to put on screen.
313 ///
314 /// Two rules, both load-bearing:
315 ///
316 /// 1. Only the **root cause** is used. Our own `with_context` strings are the
317 /// ones that interpolate `settings.toml`'s absolute path; the underlying
318 /// `io::Error` ("Permission denied (os error 13)") carries the part the user
319 /// actually needs.
320 /// 2. Anything that still looks like a path is replaced. A home directory can
321 /// contain a real name, and a status toast is the one place in the TUI that
322 /// ends up in screenshots and bug reports. Truncation keeps a pathological
323 /// error from taking over the footer.
324 fn safe_error_detail(err: &anyhow::Error) -> String {
325 const MAX: usize = 160;
326 let raw = err.root_cause().to_string();
327 let scrubbed = raw
328 .split_whitespace()
329 .map(|token| {
330 let looks_like_path = token.contains('/')
331 || token.contains('\\')
332 || (token.len() > 2 && token.as_bytes()[1] == b':');
333 if looks_like_path { "<path>" } else { token }
334 })
335 .collect::<Vec<_>>()
336 .join(" ");
337 if scrubbed.chars().count() > MAX {
338 let truncated: String = scrubbed.chars().take(MAX).collect();
339 format!("{truncated}…")
340 } else {
341 scrubbed
342 }
343 }
344
345 /// The single serialized owner of startup-default writes for one `App`.
346 ///
347 /// Cheap to clone; every clone shares the same queue, write mutex, and failure
348 /// mailbox. See the module docs for why ordering comes from the enqueue rather
349 /// than from task scheduling.
350 #[derive(Debug, Clone, Default)]
351 pub struct StartupDefaultsWriter {
352 inner: Arc<WriterInner>,
353 }
354
355 #[derive(Debug, Default)]
356 struct WriterInner {
357 /// Pending updates in user-action order. Only ever popped while `write` is
358 /// held, so a drain is a strict prefix of this queue.
359 queue: Mutex<VecDeque<StartupDefaults>>,
360 /// Held across an entire load / modify / save, so transactions never
361 /// interleave.
362 write: Mutex<()>,
363 failures: StartupDefaultFailures,
364 }
365
366 impl StartupDefaultsWriter {
367 /// Queue `update` and persist it off the event loop.
368 ///
369 /// Returns immediately: the queue push is the only work done on the calling
370 /// thread, so keystroke-rate actions never wait on disk. When no tokio
371 /// runtime is running (unit tests, and the non-async construction paths
372 /// that mirror `file_picker`'s scan fallback) the drain happens inline so
373 /// behavior stays observable and deterministic.
374 pub fn spawn(&self, update: StartupDefaults) {
375 if update.is_empty() {
376 return;
377 }
378 // Checked *before* the enqueue: an unauthorized test must leave no trace
379 // at all, so a later authorized drain cannot inherit its work and so it
380 // never takes out a claim another test would have to wait on. Always
381 // true in production.
382 if !spawn_writes_permitted() {
383 return;
384 }
385 if tokio::runtime::Handle::try_current().is_err() {
386 // No runtime (unit tests, and the non-async construction paths that
387 // mirror `file_picker`'s scan fallback): drain inline so behavior
388 // stays observable and deterministic.
389 self.lock_queue().push_back(update);
390 self.drain_pending();
391 return;
392 }
393 // Captured on the *calling* thread, which under `cfg(test)` is the
394 // sealed-`HOME` test thread. It carries that test's env scope into the
395 // blocking pool and keeps that scope's write gate open until the drain is
396 // finished. See the module docs for why both matter.
397 #[cfg(test)]
398 let ticket = match TestDrainTicket::capture() {
399 Some(ticket) => ticket,
400 None => {
401 // Authorized to write, but not the env scope's *owner*, so this
402 // thread cannot hand the scope to a worker. Handing the write to
403 // an unenrolled background thread would park it on the sealing
404 // test's env lock; this thread is already inside the sealed
405 // environment, so write here instead of skipping.
406 self.lock_queue().push_back(update);
407 self.drain_pending();
408 return;
409 }
410 };
411 self.lock_queue().push_back(update);
412 let writer = self.clone();
413 codewhale_util::utils::spawn_blocking_supervised("startup-defaults-persist", move || {
414 #[cfg(test)]
415 let _scope = ticket.enter();
416 writer.drain_pending();
417 });
418 }
419
420 /// Persist `update` on the calling thread and report whether it landed.
421 ///
422 /// Used by the model and effort pickers, which record a setup receipt whose
423 /// honesty depends on knowing the write succeeded. Anything the user did
424 /// *before* this call is already queued and is applied first, under the
425 /// same lock, so this cannot silently overwrite a newer selection.
426 pub fn apply_blocking(&self, update: StartupDefaults) -> anyhow::Result<()> {
427 let _write = self.lock_write();
428 self.drain_locked();
429 if update.is_empty() {
430 return Ok(());
431 }
432 update.apply()
433 }
434
435 /// Block until the queue is empty and no transaction is in flight.
436 ///
437 /// Available in production, not only in tests: at shutdown the last thing
438 /// the user did may still be sitting in the queue, and the process is about
439 /// to exit. Taking the write lock and draining here is a join — a
440 /// background task that already holds the lock finishes first, and anything
441 /// still queued is applied on this thread.
442 ///
443 /// Never call this from a thread that holds a settings transaction; see the
444 /// no-deadlock contract in the module docs.
445 pub fn flush(&self) {
446 let _write = self.lock_write();
447 self.drain_locked();
448 }
449
450 /// Flush at process shutdown and hand back everything that failed.
451 ///
452 /// Returns the failures instead of toasting them because the caller is past
453 /// the last redraw: the TUI's toast surface will never be painted again, so
454 /// the only honest way to report is on the restored terminal after the
455 /// alternate screen is gone.
456 #[must_use]
457 pub fn shutdown(&self) -> Vec<StartupDefaultFailure> {
458 self.flush();
459 self.drain_failures()
460 }
461
462 /// How many updates are queued but not yet applied. Tests use it to prove
463 /// an unauthorized caller enqueued *nothing*, rather than enqueuing work a
464 /// later drain could inherit.
465 #[cfg(test)]
466 pub(crate) fn pending_len(&self) -> usize {
467 self.lock_queue().len()
468 }
469
470 /// Drain any pending failures for display.
471 pub fn drain_failures(&self) -> Vec<StartupDefaultFailure> {
472 self.inner.failures.drain()
473 }
474
475 fn drain_pending(&self) {
476 let _write = self.lock_write();
477 self.drain_locked();
478 }
479
480 /// Apply every queued update in FIFO order. Caller holds the write lock.
481 fn drain_locked(&self) {
482 loop {
483 let Some(update) = self.lock_queue().pop_front() else {
484 return;
485 };
486 // Re-check the test gate at apply time, not just at enqueue time.
487 // `TestWriteGuard` now waits for outstanding drains, so a straggler
488 // from a *gated* test can no longer reach here after its `HOME`
489 // guard is gone. This stays as the backstop for the untracked
490 // paths — an inline drain reached from a later, ungated test, or a
491 // queue entry that survived a panicking transaction.
492 if !spawn_writes_permitted() {
493 continue;
494 }
495 update.apply_reporting(&self.inner.failures);
496 }
497 }
498
499 /// Take the transaction lock.
500 ///
501 /// A panic inside one transaction must not wedge persistence for the rest
502 /// of the session; the mutex protects ordering, not invariants, so a
503 /// poisoned guard is recovered rather than propagated.
504 #[cfg(not(test))]
505 fn lock_write(&self) -> MutexGuard<'_, ()> {
506 self.inner
507 .write
508 .lock()
509 .unwrap_or_else(std::sync::PoisonError::into_inner)
510 }
511
512 /// Test build of `lock_write`, with a watchdog.
513 ///
514 /// Production blocks indefinitely, which is correct: the only thing ahead
515 /// of it is a bounded settings transaction. In a test binary an indefinite
516 /// wait is indistinguishable from the lock-order inversion described in the
517 /// module docs, and a hung test job reports nothing. Polling with a deadline
518 /// is not a synchronization device — every acquisition below is expected to
519 /// succeed on the first `try_lock` or shortly after — it exists purely so a
520 /// regression fails loudly.
521 #[cfg(test)]
522 fn lock_write(&self) -> MutexGuard<'_, ()> {
523 use std::sync::TryLockError;
524
525 let deadline = std::time::Instant::now() + WRITE_LOCK_TEST_DEADLINE;
526 loop {
527 match self.inner.write.try_lock() {
528 Ok(guard) => return guard,
529 Err(TryLockError::Poisoned(poisoned)) => return poisoned.into_inner(),
530 Err(TryLockError::WouldBlock) => {}
531 }
532 assert!(
533 std::time::Instant::now() < deadline,
534 "startup-defaults write lock was not released within {WRITE_LOCK_TEST_DEADLINE:?}. \
535 Some thread is holding it across a settings transaction that cannot finish — \
536 usually because it is blocked on a lock this test already holds (see the \
537 no-deadlock contract in tui::startup_defaults)."
538 );
539 std::thread::sleep(std::time::Duration::from_millis(1));
540 }
541 }
542
543 fn lock_queue(&self) -> MutexGuard<'_, VecDeque<StartupDefaults>> {
544 self.inner
545 .queue
546 .lock()
547 .unwrap_or_else(std::sync::PoisonError::into_inner)
548 }
549 }
550
551 /// Whether the fire-and-forget [`StartupDefaultsWriter::spawn`] path may touch
552 /// disk *on the calling thread's behalf*.
553 ///
554 /// Mode and thinking cycling happen inside a great many `App` unit tests that do
555 /// not seal `HOME`. Those tests predate this write and must not start rewriting
556 /// the developer's real `~/.codewhale/settings.toml`, so under `cfg(test)` the
557 /// background write is inert unless the caller is inside a sealed env scope that
558 /// opted in with `allow_writes_in_tests`.
559 ///
560 /// **This is deliberately not a process-global flag.** A global bool is true for
561 /// as long as *any* test has opted in, so an unrelated test running in parallel
562 /// would pass the gate, resolve no env scope of its own, and then block on the
563 /// sealed test's env lock inside path resolution — while the sealed test's guard
564 /// waited for that very drain to finish. Authorization is therefore keyed to the
565 /// concrete env-scope generation the write belongs to, and only a thread that is
566 /// actually inside that scope (its owner, or a worker it adopted) is permitted.
567 ///
568 /// In production this is unconditionally true: a real write is never skipped.
569 ///
570 /// The synchronous [`StartupDefaultsWriter::apply_blocking`] path is not gated:
571 /// its callers (the model/effort pickers) seal `HOME` themselves and need to
572 /// know whether the write landed.
573 fn spawn_writes_permitted() -> bool {
574 #[cfg(test)]
575 {
576 authorized_test_write_generation().is_some()
577 }
578 #[cfg(not(test))]
579 {
580 true
581 }
582 }
583
584 /// The env-scope generation the calling thread is authorized to write for, if
585 /// any: it must be inside a live env scope *and* that scope must be the one a
586 /// live [`TestWriteGuard`] opened.
587 #[cfg(test)]
588 fn authorized_test_write_generation() -> Option<u64> {
589 let generation = crate::test_support::current_env_scope_generation()?;
590 let scopes = lock_test_write_scopes();
591 scopes
592 .authorized
593 .contains(&generation)
594 .then_some(generation)
595 }
596
597 /// How long a test may wait for the transaction lock, or for outstanding
598 /// background drains, before it is treated as wedged. Every real wait here is
599 /// sub-millisecond; this only has to be shorter than a CI job timeout and
600 /// longer than any honest settings write.
601 #[cfg(test)]
602 const WRITE_LOCK_TEST_DEADLINE: std::time::Duration = std::time::Duration::from_secs(15);
603
604 /// Which env-scope generations may write, and how many background drains each
605 /// one still has outstanding.
606 ///
607 /// Keyed by generation so a guard only ever waits for the drains *it* authorized.
608 /// Sharing one count across all tests is what let a sealed test's `drop` block
609 /// on a foreign test's queued work.
610 #[cfg(test)]
611 #[derive(Default)]
612 struct TestWriteScopes {
613 authorized: Vec<u64>,
614 outstanding: Vec<(u64, usize)>,
615 }
616
617 #[cfg(test)]
618 impl TestWriteScopes {
619 fn outstanding_for(&self, generation: u64) -> usize {
620 self.outstanding
621 .iter()
622 .find(|(scope, _)| *scope == generation)
623 .map_or(0, |(_, count)| *count)
624 }
625
626 fn adjust(&mut self, generation: u64, delta: isize) {
627 if let Some(entry) = self
628 .outstanding
629 .iter_mut()
630 .find(|(scope, _)| *scope == generation)
631 {
632 entry.1 = entry.1.saturating_add_signed(delta);
633 if entry.1 == 0 {
634 self.outstanding.retain(|(scope, _)| *scope != generation);
635 }
636 } else if delta > 0 {
637 self.outstanding.push((generation, delta as usize));
638 }
639 }
640 }
641
642 #[cfg(test)]
643 fn test_write_scopes() -> &'static (Mutex<TestWriteScopes>, std::sync::Condvar) {
644 static SCOPES: std::sync::OnceLock<(Mutex<TestWriteScopes>, std::sync::Condvar)> =
645 std::sync::OnceLock::new();
646 SCOPES.get_or_init(|| {
647 (
648 Mutex::new(TestWriteScopes::default()),
649 std::sync::Condvar::new(),
650 )
651 })
652 }
653
654 #[cfg(test)]
655 fn lock_test_write_scopes() -> MutexGuard<'static, TestWriteScopes> {
656 test_write_scopes()
657 .0
658 .lock()
659 .unwrap_or_else(std::sync::PoisonError::into_inner)
660 }
661
662 /// Opt the calling test's sealed env scope into real background startup-default
663 /// writes.
664 ///
665 /// Callers must already hold `test_support::lock_test_env()` and have sealed
666 /// `HOME`. Panics otherwise, because an ungated opt-in would authorize writes
667 /// into the developer's real settings file.
668 #[cfg(test)]
669 pub(crate) fn allow_writes_in_tests() -> TestWriteGuard {
670 let generation = crate::test_support::current_env_scope_generation().expect(
671 "allow_writes_in_tests() requires the calling thread to hold \
672 test_support::lock_test_env() with a sealed HOME",
673 );
674 let mut scopes = lock_test_write_scopes();
675 if !scopes.authorized.contains(&generation) {
676 scopes.authorized.push(generation);
677 }
678 drop(scopes);
679 TestWriteGuard { generation }
680 }
681
682 #[cfg(test)]
683 pub(crate) struct TestWriteGuard {
684 generation: u64,
685 }
686
687 #[cfg(test)]
688 impl Drop for TestWriteGuard {
689 /// Close this scope's gate only once every drain *this scope* handed to the
690 /// blocking pool has finished.
691 ///
692 /// The drain re-checks authorization per item, which stops a straggler from
693 /// writing after the gate closes — but it does so by *discarding* the item,
694 /// which is a silent hole in whatever the test just asserted, and it does not
695 /// stop a straggler that is already mid-write. Waiting here makes the gate's
696 /// lifetime cover the writes it authorized.
697 ///
698 /// It cannot deadlock on a foreign test: the wait is scoped to this
699 /// generation, and every drain counted under this generation is enrolled in
700 /// this test's env scope, so none of them can be parked on a lock this
701 /// thread holds.
702 fn drop(&mut self) {
703 let drained = wait_for_outstanding_test_drains(self.generation);
704 let mut scopes = lock_test_write_scopes();
705 scopes.authorized.retain(|scope| *scope != self.generation);
706 drop(scopes);
707 // Report the timeout as a failure, but never as a second panic during
708 // an unwind — that aborts the whole test binary and hides the real
709 // assertion that started it.
710 assert!(
711 drained || std::thread::panicking(),
712 "background startup-default drain(s) for env scope {} did not finish within \
713 {WRITE_LOCK_TEST_DEADLINE:?}; see the no-deadlock contract in \
714 tui::startup_defaults",
715 self.generation
716 );
717 }
718 }
719
720 /// Wait for every drain authorized by `generation`, returning `false` if the
721 /// deadline expired first. Never panics: the caller decides how to report a
722 /// timeout.
723 #[cfg(test)]
724 fn wait_for_outstanding_test_drains(generation: u64) -> bool {
725 let (scopes, done) = test_write_scopes();
726 let mut guard = scopes
727 .lock()
728 .unwrap_or_else(std::sync::PoisonError::into_inner);
729 let deadline = std::time::Instant::now() + WRITE_LOCK_TEST_DEADLINE;
730 while guard.outstanding_for(generation) > 0 {
731 let remaining = deadline.saturating_duration_since(std::time::Instant::now());
732 if remaining.is_zero() {
733 return false;
734 }
735 let (next, _timeout) = done
736 .wait_timeout(guard, remaining)
737 .unwrap_or_else(std::sync::PoisonError::into_inner);
738 guard = next;
739 }
740 true
741 }
742
743 /// One background drain's claim on the enclosing test: its env scope, and its
744 /// slot in that scope's outstanding-drain count.
745 ///
746 /// Minted only when the spawning thread is authorized, so an unauthorized test
747 /// never enqueues work and never takes out a claim it would then have to be
748 /// waited on for. Captured on the spawning thread and moved into the blocking
749 /// task, so the count is decremented whether the task ran or the runtime shut
750 /// down and dropped it un-run.
751 #[cfg(test)]
752 struct TestDrainTicket {
753 env: crate::test_support::EnvScopeTicket,
754 }
755
756 #[cfg(test)]
757 impl TestDrainTicket {
758 /// `None` when the caller is not the owner of an authorized env scope — the
759 /// caller must then not enqueue anything.
760 fn capture() -> Option<Self> {
761 let generation = authorized_test_write_generation()?;
762 let env = crate::test_support::env_scope_ticket()?;
763 // Only the scope owner can hand its scope to a worker, and the ticket
764 // must describe the same generation we just authorized.
765 if env.generation() != generation {
766 return None;
767 }
768 lock_test_write_scopes().adjust(generation, 1);
769 Some(Self { env })
770 }
771
772 fn enter(&self) -> Option<crate::test_support::EnvScopeMembership> {
773 crate::test_support::join_env_scope(Some(self.env))
774 }
775 }
776
777 #[cfg(test)]
778 impl Drop for TestDrainTicket {
779 fn drop(&mut self) {
780 let (scopes, done) = test_write_scopes();
781 let mut guard = scopes
782 .lock()
783 .unwrap_or_else(std::sync::PoisonError::into_inner);
784 guard.adjust(self.env.generation(), -1);
785 drop(guard);
786 done.notify_all();
787 }
788 }
789
790 /// Mailbox for non-blocking startup-default write failures.
791 ///
792 /// The event loop drains this every iteration so a failed write becomes a
793 /// visible warning instead of a silent revert on the next launch, and shutdown
794 /// drains it one last time so a write that failed after the final redraw is
795 /// still reported.
796 #[derive(Debug, Clone, Default)]
797 pub struct StartupDefaultFailures(Arc<Mutex<Vec<StartupDefaultFailure>>>);
798
799 impl StartupDefaultFailures {
800 fn record(&self, failure: StartupDefaultFailure) {
801 // A poisoned mailbox must not take down the writer thread; the write
802 // itself already happened (or failed) and was logged.
803 if let Ok(mut guard) = self.0.lock() {
804 guard.push(failure);
805 }
806 }
807
808 /// Take every pending failure, leaving the mailbox empty.
809 pub fn drain(&self) -> Vec<StartupDefaultFailure> {
810 self.0
811 .lock()
812 .map(|mut guard| std::mem::take(&mut *guard))
813 .unwrap_or_default()
814 }
815 }
816
817 #[cfg(test)]
818 mod tests {
819 use super::*;
820
821 #[test]
822 fn mode_update_only_targets_default_mode() {
823 let update = StartupDefaults::mode(AppMode::Plan);
824 assert_eq!(update.mode, Some("plan"));
825 assert!(update.reasoning_effort.is_none());
826 assert_eq!(update.subjects(), vec![StartupDefaultSubject::Mode]);
827 }
828
829 #[test]
830 fn subjects_stay_typed_for_a_combined_mode_and_thinking_update() {
831 let update = StartupDefaults::mode(AppMode::Plan).with_reasoning_effort("high");
832 assert_eq!(
833 update.subjects(),
834 vec![StartupDefaultSubject::Mode, StartupDefaultSubject::Thinking,]
835 );
836 }
837
838 /// A failure toast is one of the few strings that reliably ends up in a
839 /// screenshot, so the detail must not carry the settings path (which
840 /// contains the user's home directory, and often their real name).
841 #[test]
842 fn safe_error_detail_keeps_the_cause_and_drops_the_path() {
843 let err = anyhow::anyhow!("Permission denied (os error 13)")
844 .context("Failed to write settings to /Users/real-name/.codewhale/settings.toml");
845 let detail = safe_error_detail(&err);
846 assert_eq!(detail, "Permission denied (os error 13)");
847 assert!(!detail.contains("real-name"));
848 assert!(!detail.contains(".codewhale"));
849
850 // Even when the root cause itself names a path, nothing path-shaped
851 // survives.
852 let rooted = anyhow::anyhow!("cannot open /Users/real-name/.codewhale/settings.toml");
853 let scrubbed = safe_error_detail(&rooted);
854 assert_eq!(scrubbed, "cannot open <path>");
855 }
856
857 #[test]
858 fn empty_update_is_a_no_op() {
859 assert!(StartupDefaults::default().is_empty());
860 StartupDefaults::default()
861 .apply()
862 .expect("empty update must not touch disk");
863 }
864
865 #[test]
866 fn failure_mailbox_drains_once() {
867 let failures = StartupDefaultFailures::default();
868 let failure = StartupDefaultFailure {
869 subjects: vec![StartupDefaultSubject::Mode],
870 detail: "boom".to_string(),
871 };
872 failures.record(failure.clone());
873 assert_eq!(failures.drain(), vec![failure]);
874 assert!(failures.drain().is_empty());
875 }
876
877 /// The deadlock this module shipped with, reduced to its two threads.
878 ///
879 /// A worker takes the transaction lock and runs a settings transaction
880 /// while the test thread — which holds the process-wide env lock for its
881 /// whole body — waits for that worker. Before `spawn` enrolled its drain in
882 /// the test's env scope, the worker parked inside
883 /// `settings_path_candidates` holding `write`, the test thread parked on
884 /// `write`, and the test hung instead of failing.
885 ///
886 /// The channel is the barrier: a regression makes `recv_timeout` expire and
887 /// the test *fails*, with no thread left for CI to wait on.
888 #[test]
889 fn a_worker_enrolled_in_the_test_env_scope_completes_a_transaction() {
890 use std::sync::mpsc;
891 use std::time::Duration;
892
893 let _lock = crate::test_support::lock_test_env();
894 let tmp = tempfile::TempDir::new().expect("tempdir");
895 let _home = crate::test_support::EnvVarGuard::set("HOME", tmp.path());
896 let _user_profile = crate::test_support::EnvVarGuard::set("USERPROFILE", tmp.path());
897 let _codewhale_home =
898 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path().join(".codewhale"));
899 let _deepseek_config = crate::test_support::EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH");
900 let _codewhale_config = crate::test_support::EnvVarGuard::remove("CODEWHALE_CONFIG_PATH");
901 let _writes = allow_writes_in_tests();
902
903 let writer = StartupDefaultsWriter::default();
904 let ticket = crate::test_support::env_scope_ticket();
905 assert!(
906 ticket.is_some(),
907 "the thread holding lock_test_env must be able to mint a scope ticket"
908 );
909
910 let (done_tx, done_rx) = mpsc::channel();
911 let worker = writer.clone();
912 let handle = std::thread::spawn(move || {
913 let _membership = crate::test_support::join_env_scope(ticket);
914 let result = worker.apply_blocking(StartupDefaults::mode(AppMode::Plan));
915 done_tx.send(result).ok();
916 });
917
918 let result = done_rx
919 .recv_timeout(Duration::from_secs(10))
920 .expect("an enrolled worker must not block on the env lock its own test holds");
921 result.expect("the transaction must land");
922 handle.join().expect("worker thread");
923
924 // Reachable from the env-lock holder for the same reason.
925 writer.flush();
926
927 // Proof the worker resolved the *sealed* settings path rather than
928 // falling back to the isolated root a foreign reader would get.
929 assert_eq!(
930 Settings::load_persisted()
931 .expect("reload settings")
932 .default_mode,
933 "plan"
934 );
935 assert!(tmp.path().join(".codewhale/settings.toml").exists());
936 }
937
938 /// Seal `HOME`/`CODEWHALE_HOME` onto `tmp`. Caller must already hold
939 /// `lock_test_env()`.
940 fn seal_home(tmp: &std::path::Path) -> Vec<crate::test_support::EnvVarGuard> {
941 use crate::test_support::EnvVarGuard;
942 vec![
943 EnvVarGuard::set("HOME", tmp),
944 EnvVarGuard::set("USERPROFILE", tmp),
945 EnvVarGuard::set("CODEWHALE_HOME", tmp.join(".codewhale")),
946 EnvVarGuard::remove("DEEPSEEK_CONFIG_PATH"),
947 EnvVarGuard::remove("CODEWHALE_CONFIG_PATH"),
948 ]
949 }
950
951 /// The second deadlock the scoped gate exists to prevent.
952 ///
953 /// A process-global "writes enabled" bool is true for as long as *any* test
954 /// has opted in. An unrelated test running in parallel — no env lock of its
955 /// own, so no sealed `HOME` — would therefore pass the gate, enqueue an
956 /// update, and hand it to a blocking thread that could mint no env-scope
957 /// ticket. That thread then parked inside `settings_path_candidates` waiting
958 /// for the env lock *this* test holds, while this test's `TestWriteGuard`
959 /// drop waited for that same drain to finish: a 15-second mutual wait ending
960 /// in a failure that pointed at the wrong test.
961 ///
962 /// Two things are asserted, both of which used to be false:
963 ///
964 /// 1. The unauthorized thread returns promptly instead of blocking. The
965 /// channel is the barrier — a regression expires `recv_timeout` and the
966 /// test *fails* rather than hanging CI.
967 /// 2. It leaves nothing behind: no queue entry (which a later authorized
968 /// drain would inherit and write), no outstanding-drain claim, and no
969 /// settings file — in particular not the developer's real one.
970 #[test]
971 fn an_unauthorized_thread_neither_writes_nor_waits_for_a_sealed_scope() {
972 use std::sync::mpsc;
973 use std::time::Duration;
974
975 let _lock = crate::test_support::lock_test_env();
976 let tmp = tempfile::TempDir::new().expect("tempdir");
977 let _env = seal_home(tmp.path());
978 let _writes = allow_writes_in_tests();
979
980 let writer = StartupDefaultsWriter::default();
981 let foreign = writer.clone();
982 let (done_tx, done_rx) = mpsc::channel();
983 let handle = std::thread::spawn(move || {
984 // Deliberately *not* enrolled: this is the shape of an unrelated
985 // `App` test calling `select_mode` while another test is sealed.
986 foreign.spawn(StartupDefaults::mode(AppMode::Plan));
987 done_tx.send(()).ok();
988 });
989 done_rx
990 .recv_timeout(Duration::from_secs(5))
991 .expect("an unauthorized writer must return immediately, never block on the env lock");
992 handle.join().expect("foreign thread");
993
994 assert_eq!(
995 writer.pending_len(),
996 0,
997 "an unauthorized caller must not enqueue work an authorized drain could inherit"
998 );
999 assert!(
1000 !tmp.path().join(".codewhale/settings.toml").exists(),
1001 "an unauthorized caller must not write any settings file"
1002 );
1003
1004 // The sealed scope itself is unaffected: its own write still lands, and
1005 // its guard has nothing foreign to wait for.
1006 writer
1007 .apply_blocking(StartupDefaults::mode(AppMode::Plan))
1008 .expect("the sealed scope's own write must land");
1009 assert_eq!(
1010 Settings::load_persisted()
1011 .expect("reload settings")
1012 .default_mode,
1013 "plan"
1014 );
1015 }
1016
1017 /// Two sealed scopes must not be able to authorize, or wait for, each
1018 /// other's work.
1019 ///
1020 /// The env mutex means two sealed bodies never overlap, but their *drains*
1021 /// can: a straggler handed to the blocking pool by scope N can still be
1022 /// alive when scope N+1 opens. With one global flag and one global
1023 /// outstanding count, scope N+1 inherited both — it could write under scope
1024 /// N's authorization, and either guard could block on the other's work.
1025 /// Authorization and drain accounting are keyed to the env-scope generation
1026 /// so neither is possible.
1027 #[test]
1028 fn two_sealed_scopes_share_neither_write_authorization_nor_drain_accounting() {
1029 let first_generation;
1030 let stale_ticket;
1031
1032 {
1033 let _lock = crate::test_support::lock_test_env();
1034 let tmp = tempfile::TempDir::new().expect("tempdir");
1035 let _env = seal_home(tmp.path());
1036 let _writes = allow_writes_in_tests();
1037
1038 first_generation = crate::test_support::current_env_scope_generation()
1039 .expect("a sealed scope must have a generation");
1040 stale_ticket = crate::test_support::env_scope_ticket();
1041 assert_eq!(
1042 authorized_test_write_generation(),
1043 Some(first_generation),
1044 "the scope that opted in must be the one authorized"
1045 );
1046
1047 let writer = StartupDefaultsWriter::default();
1048 writer
1049 .apply_blocking(StartupDefaults::mode(AppMode::Plan))
1050 .expect("first scope's write must land");
1051 assert_eq!(
1052 Settings::load_persisted().expect("reload").default_mode,
1053 "plan"
1054 );
1055 assert_eq!(
1056 lock_test_write_scopes().outstanding_for(first_generation),
1057 0,
1058 "the first scope must have no outstanding drain left to wait on"
1059 );
1060 }
1061
1062 {
1063 let _lock = crate::test_support::lock_test_env();
1064 let tmp = tempfile::TempDir::new().expect("tempdir");
1065 let _env = seal_home(tmp.path());
1066
1067 let second_generation = crate::test_support::current_env_scope_generation()
1068 .expect("a sealed scope must have a generation");
1069 assert_ne!(
1070 second_generation, first_generation,
1071 "each acquisition must open a fresh generation"
1072 );
1073 assert_eq!(
1074 authorized_test_write_generation(),
1075 None,
1076 "a new scope must not inherit the previous scope's opt-in"
1077 );
1078 assert!(
1079 crate::test_support::join_env_scope(stale_ticket).is_none(),
1080 "a ticket from a closed scope must not enroll a thread in the current one"
1081 );
1082
1083 // Without its own opt-in, this scope's background path stays inert
1084 // and writes nothing — not even into its own sealed HOME.
1085 let writer = StartupDefaultsWriter::default();
1086 writer.spawn(StartupDefaults::mode(AppMode::Plan));
1087 assert_eq!(writer.pending_len(), 0);
1088 assert!(!tmp.path().join(".codewhale/settings.toml").exists());
1089
1090 // With its own opt-in it writes into *its* home, keyed to *its*
1091 // generation.
1092 let _writes = allow_writes_in_tests();
1093 assert_eq!(authorized_test_write_generation(), Some(second_generation));
1094 writer.spawn(StartupDefaults::mode(AppMode::Plan));
1095 writer.flush();
1096 assert_eq!(
1097 Settings::load_persisted().expect("reload").default_mode,
1098 "plan"
1099 );
1100 assert!(tmp.path().join(".codewhale/settings.toml").exists());
1101 }
1102 }
1103
1104 /// The transactional boundary is `Settings::transact`, not this writer's own
1105 /// mutex.
1106 ///
1107 /// A direct settings writer holds the transaction across its whole
1108 /// load / modify / save. A concurrent startup-default drain must not be able
1109 /// to slip a save in between — if it could, this test's `save` would write
1110 /// back a pre-image and silently revert the queued selection, which is
1111 /// exactly how `default_mode` was lost to a Shift+Tab posture write.
1112 #[test]
1113 fn a_direct_writer_holds_the_boundary_against_a_queued_startup_default() {
1114 let _lock = crate::test_support::lock_test_env();
1115 let tmp = tempfile::TempDir::new().expect("tempdir");
1116 let _env = seal_home(tmp.path());
1117 let _writes = allow_writes_in_tests();
1118
1119 let writer = StartupDefaultsWriter::default();
1120 let ticket = crate::test_support::env_scope_ticket();
1121
1122 let mut handle = None;
1123 codewhale_runtime::settings::with_settings_transaction(|transaction| {
1124 let mut direct = transaction.load().expect("load inside the transaction");
1125 // A field with a non-default value, so the final assertion cannot
1126 // pass by accident: `max_input_history` defaults to 100.
1127 direct
1128 .set("max_history", "321")
1129 .expect("set an unrelated field");
1130
1131 // A drain on another thread, enrolled so it resolves the sealed
1132 // path. It must block on the transaction above rather than
1133 // interleave.
1134 let queued = writer.clone();
1135 handle = Some(std::thread::spawn(move || {
1136 let _membership = crate::test_support::join_env_scope(ticket);
1137 queued
1138 .apply_blocking(StartupDefaults::mode(AppMode::Plan))
1139 .expect("the queued write must land once the boundary is released");
1140 }));
1141
1142 // Give the worker a real chance to reach (and be refused by) the
1143 // boundary. This is not the assertion's synchronization — the
1144 // assertion is that the value is *still absent*, which a sleep can
1145 // only make easier to violate.
1146 std::thread::sleep(std::time::Duration::from_millis(150));
1147 assert_eq!(
1148 transaction.load().expect("re-read").default_mode,
1149 Settings::default().default_mode,
1150 "no other writer may save while a transaction is open"
1151 );
1152
1153 transaction.save(&direct).expect("commit the direct write");
1154 Ok(())
1155 })
1156 .expect("the direct transaction must complete");
1157 handle
1158 .expect("worker spawned")
1159 .join()
1160 .expect("queued writer thread");
1161
1162 let settled = Settings::load_persisted().expect("reload");
1163 assert_eq!(
1164 settled.max_input_history, 321,
1165 "the direct write must survive the queued startup-default write"
1166 );
1167 assert_eq!(
1168 settled.default_mode, "plan",
1169 "the queued startup-default write must survive the direct write"
1170 );
1171 }
1172 }
1173
1173 lines RUST