返回 CodeWhale
mod.rs
根目录 / crates / tui / src / tui / onboarding / mod.rs
1 //! Calm first-run onboarding: one decision per screen.
2 //!
3 //! The flow asks only for what Codewhale genuinely needs before the user can
4 //! begin: language (only when it cannot be confidently inferred from settings
5 //! or the environment), a provider/model route (only when no usable route is
6 //! configured), and workspace trust (only when a decision is required).
7 //! Appearance, command tours, mode primers, and tips stay in `/setup` and
8 //! contextual help so nothing delays first use. The last screen hands the
9 //! user the real composer pre-seeded with a first task for this folder.
10
11 pub mod language;
12 pub mod trust_directory;
13 pub mod welcome;
14
15 use std::path::{Path, PathBuf};
16
17 use ratatui::{
18 Frame,
19 layout::Rect,
20 style::{Color, Modifier, Style},
21 text::{Line, Span},
22 widgets::Paragraph,
23 };
24
25 use crate::tui::app::{App, OnboardingState};
26 use crate::tui::views::ActionHint;
27 use crate::tui::views::rounded::{
28 render_rounded_footer_themed, render_rounded_surface_themed, resolved_surface_bg,
29 };
30 use codewhale_localization::MessageId;
31 use codewhale_palette as palette;
32
33 const ONBOARDED_MARKER_FILE: &str = ".onboarded";
34
35 const CODE_PROJECT_MARKERS: &[&str] = &[
36 "Cargo.toml",
37 "package.json",
38 "pyproject.toml",
39 "setup.py",
40 "go.mod",
41 "deno.json",
42 "composer.json",
43 ];
44
45 pub fn render(f: &mut Frame, area: Rect, app: &App) {
46 let title = app.tr(MessageId::OnboardStepsTitle).into_owned();
47 let progress = required_progress(app).map(|(current, total)| format!("{current}/{total}"));
48 let hints = action_hints(app);
49 let buf = f.buffer_mut();
50 let inner =
51 render_rounded_surface_themed(area, buf, title, progress, true, Some(&app.ui_theme));
52 let bg = resolved_surface_bg(&app.ui_theme);
53 let border = if app.ui_theme.border != Color::Reset {
54 app.ui_theme.border
55 } else {
56 palette::BORDER_COLOR
57 };
58 let content = render_rounded_footer_themed(inner, buf, &hints, bg, border);
59 let lane = reading_lane(content, app.onboarding);
60 let lines = screen_lines(app, usize::from(lane.width), usize::from(lane.height));
61 if lines.is_empty() {
62 return;
63 }
64 let body = center_vertically(lane, lines.len());
65 f.render_widget(Paragraph::new(lines), body);
66 }
67
68 fn reading_lane(area: Rect, state: OnboardingState) -> Rect {
69 if state == OnboardingState::Language || area.width <= 76 {
70 return area;
71 }
72 let width = 72u16.min(area.width);
73 let pad = area.width.saturating_sub(width) / 2;
74 Rect {
75 x: area.x.saturating_add(pad),
76 width,
77 ..area
78 }
79 }
80
81 fn center_vertically(area: Rect, rows: usize) -> Rect {
82 let pad = (area
83 .height
84 .saturating_sub(u16::try_from(rows).unwrap_or(area.height)))
85 / 2;
86 Rect {
87 y: area.y.saturating_add(pad),
88 height: area.height.saturating_sub(pad),
89 ..area
90 }
91 }
92
93 pub(super) fn theme_or(color: Color, fallback: Color) -> Color {
94 if color != Color::Reset {
95 color
96 } else {
97 fallback
98 }
99 }
100
101 /// The hairline surface title counts only the REQUIRED decisions left in
102 /// this run — never a "Step 1/7" spine. Screens that are not themselves a
103 /// required decision (welcome, ready) show no counter. A decision drops out
104 /// of the count once it is satisfied, so the counter only ever moves
105 /// forward.
106 fn required_progress(app: &App) -> Option<(usize, usize)> {
107 // The counter's denominator is every required decision this run, not
108 // only the ones still ahead: advancing past the language screen must
109 // not shrink "1 of 2" into a bare "1 of 1".
110 let mut steps = Vec::new();
111 if app.onboarding_had_language_step {
112 steps.push(OnboardingState::Language);
113 }
114 if app.onboarding_had_provider_step {
115 steps.push(OnboardingState::Provider);
116 }
117 if app.onboarding_had_trust_step {
118 steps.push(OnboardingState::TrustDirectory);
119 }
120 if steps.len() < 2 {
121 return None;
122 }
123 let current = steps.iter().position(|step| *step == app.onboarding)?;
124 Some((current + 1, steps.len()))
125 }
126
127 fn trust_decision_required(app: &App) -> bool {
128 !app.trust_mode && codewhale_runtime::config::needs_trust(&app.workspace)
129 }
130
131 fn action_hints(app: &App) -> Vec<ActionHint> {
132 match app.onboarding {
133 OnboardingState::Welcome => vec![
134 ActionHint::new("Enter", app.tr(MessageId::OnboardWelcomeBegin).to_string()),
135 ActionHint::new("Ctrl+C", app.tr(MessageId::OnboardActionExit).to_string()),
136 ],
137 OnboardingState::Language => vec![
138 ActionHint::new(
139 "1-9/a-g",
140 app.tr(MessageId::OnboardLanguagePick).to_string(),
141 ),
142 ActionHint::new("Enter", app.tr(MessageId::OnboardLanguageKeep).to_string()),
143 ActionHint::new("Esc", app.tr(MessageId::OnboardActionBack).to_string()),
144 ],
145 OnboardingState::Provider => vec![
146 ActionHint::new(
147 "Enter",
148 app.tr(MessageId::OnboardProviderChoose).to_string(),
149 ),
150 ActionHint::new(
151 "Ctrl+O",
152 app.tr(MessageId::OnboardProviderOffline).to_string(),
153 ),
154 ActionHint::new("Esc", app.tr(MessageId::OnboardActionBack).to_string()),
155 ],
156 OnboardingState::TrustDirectory => vec![
157 ActionHint::new("1", app.tr(MessageId::OnboardTrustActionTrust).to_string()),
158 ActionHint::new("2", app.tr(MessageId::OnboardTrustActionSkip).to_string()),
159 ActionHint::new("3", app.tr(MessageId::OnboardTrustActionQuit).to_string()),
160 ],
161 OnboardingState::Ready => vec![
162 // Only keys this screen handles: a `/rc` hint here could not be
163 // typed, because the Ready screen owns the keyboard.
164 ActionHint::new("Enter", app.tr(MessageId::OnboardReadyStart).to_string()),
165 ActionHint::new("C", app.tr(MessageId::OnboardReadyCustomize).to_string()),
166 ],
167 OnboardingState::None => Vec::new(),
168 }
169 }
170
171 pub(crate) fn render_provider_notice(f: &mut Frame, area: Rect, app: &App) -> Rect {
172 let Some(notice) = app.setup_notice() else {
173 return area;
174 };
175 if app.onboarding != OnboardingState::Provider || area.height < 2 {
176 return area;
177 }
178 let lines = wrap_words(&notice.text, usize::from(area.width.max(1)));
179 let height = u16::try_from(lines.len())
180 .unwrap_or(u16::MAX)
181 .min((area.height / 3).max(1));
182 let color = match notice.level {
183 super::app::StatusToastLevel::Error => {
184 theme_or(app.ui_theme.error_fg, palette::STATUS_ERROR)
185 }
186 super::app::StatusToastLevel::Warning => {
187 theme_or(app.ui_theme.warning, palette::STATUS_WARNING)
188 }
189 _ => theme_or(app.ui_theme.text_body, palette::TEXT_PRIMARY),
190 };
191 let header = Rect::new(area.x, area.y, area.width, height);
192 f.render_widget(
193 Paragraph::new(lines.into_iter().map(Line::from).collect::<Vec<_>>())
194 .style(Style::default().fg(color).bg(app.ui_theme.surface_bg)),
195 header,
196 );
197 Rect::new(area.x, area.y + height, area.width, area.height - height)
198 }
199
200 fn screen_lines(app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
201 let mut lines = match app.onboarding {
202 OnboardingState::Welcome => welcome::lines(app, width),
203 OnboardingState::Language => language::lines(app, width, height),
204 OnboardingState::Provider => provider_lines(app, width),
205 OnboardingState::TrustDirectory => trust_directory::lines(app, width),
206 OnboardingState::Ready => welcome::ready_lines(app, width),
207 OnboardingState::None => Vec::new(),
208 };
209 if matches!(
210 app.onboarding,
211 OnboardingState::Language | OnboardingState::Provider
212 ) && let Some(notice) = app.setup_notice()
213 && app.onboarding_key_rejected.as_deref() != Some(notice.text.as_str())
214 {
215 let color = match notice.level {
216 super::app::StatusToastLevel::Error => {
217 theme_or(app.ui_theme.error_fg, palette::STATUS_ERROR)
218 }
219 super::app::StatusToastLevel::Warning => {
220 theme_or(app.ui_theme.warning, palette::STATUS_WARNING)
221 }
222 _ => theme_or(app.ui_theme.text_body, palette::TEXT_PRIMARY),
223 };
224 let offset = lines.len().min(1);
225 lines.splice(
226 offset..offset,
227 wrap_words(&notice.text, width)
228 .into_iter()
229 .map(|segment| Line::from(Span::styled(segment, Style::default().fg(color)))),
230 );
231 }
232 lines
233 }
234
235 fn provider_lines(app: &App, width: usize) -> Vec<Line<'static>> {
236 let mut lines = Vec::new();
237 heading(&mut lines, app, MessageId::OnboardProviderTitle, width);
238 lines.push(Line::from(""));
239 if let Some(notice) = app.onboarding_key_rejected.as_deref() {
240 let error_fg = theme_or(app.ui_theme.error_fg, palette::STATUS_ERROR);
241 for segment in wrap_words(notice, width) {
242 lines.push(Line::from(Span::styled(
243 segment,
244 Style::default().fg(error_fg),
245 )));
246 }
247 lines.push(Line::from(""));
248 }
249 wrap_body(&mut lines, app, MessageId::OnboardProviderBlurb, width);
250 lines
251 }
252
253 fn heading(out: &mut Vec<Line<'static>>, app: &App, id: MessageId, width: usize) {
254 let accent = theme_or(app.ui_theme.accent_primary, palette::WHALE_ACTION);
255 for segment in wrap_words(&app.tr(id), width) {
256 out.push(Line::from(Span::styled(
257 segment,
258 Style::default().fg(accent).add_modifier(Modifier::BOLD),
259 )));
260 }
261 }
262
263 fn wrap_body(lines: &mut Vec<Line<'static>>, app: &App, id: MessageId, width: usize) {
264 let body_fg = theme_or(app.ui_theme.text_body, palette::TEXT_PRIMARY);
265 let text = app.tr(id);
266 for segment in wrap_words(&text, width) {
267 lines.push(Line::from(Span::styled(
268 segment,
269 Style::default().fg(body_fg),
270 )));
271 }
272 }
273
274 /// Characters that may not begin a line in Japanese and Chinese typography
275 /// (a small, uncontroversial kinsoku set: closing brackets, sentence-final
276 /// punctuation, and the sound-extension mark). When a width break would strand
277 /// one of these at the start of a line, carry its preceding grapheme forward.
278 const NO_LINE_START: &[char] = &[
279 '。', '、', '.', ',', ',', '。', '」', '』', ')', ']', '}', '〕', '〉', '》', '”', '’',
280 '!', '?', ':', ';', 'ー', '々', '·', '…', '!', '?', ',', '.', ':', ';', ')', ']', '}',
281 ];
282
283 /// Break one unbreakable token into lines of at most `width` display columns.
284 ///
285 /// Japanese, Chinese, and Thai do not separate words with spaces, so an entire
286 /// sentence arrives as a single token. Breaking on grapheme clusters by display
287 /// width is the conventional behaviour for those scripts and is the only way to
288 /// show the text at all; the alternative is the clip this replaces.
289 fn break_by_display_width(text: &str, width: usize) -> Vec<String> {
290 use unicode_segmentation::UnicodeSegmentation;
291 use unicode_width::UnicodeWidthStr;
292
293 let mut out: Vec<String> = Vec::new();
294 let mut current = String::new();
295 let mut current_width = 0usize;
296
297 for cluster in text.graphemes(true) {
298 let cluster_width = UnicodeWidthStr::width(cluster);
299 if current_width + cluster_width > width && !current.is_empty() {
300 let starts_forbidden = cluster
301 .chars()
302 .next()
303 .is_some_and(|c| NO_LINE_START.contains(&c));
304 if starts_forbidden {
305 // Carry the preceding text with its punctuation onto the next
306 // line. Extending a full line instead silently clips it in a
307 // terminal viewport, including on the redaction consent gate.
308 if let Some((split, _)) = current.grapheme_indices(true).rev().find(|(_, part)| {
309 !part
310 .chars()
311 .next()
312 .is_some_and(|ch| NO_LINE_START.contains(&ch))
313 }) && split > 0
314 && UnicodeWidthStr::width(&current[split..]) + cluster_width <= width
315 {
316 let carry = current.split_off(split);
317 out.push(std::mem::replace(&mut current, carry));
318 current_width = UnicodeWidthStr::width(current.as_str());
319 } else {
320 // A punctuation-only run cannot satisfy both typography
321 // and width; preserve every character inside the viewport.
322 out.push(std::mem::take(&mut current));
323 current_width = 0;
324 }
325 } else {
326 out.push(std::mem::take(&mut current));
327 current_width = 0;
328 }
329 }
330 current.push_str(cluster);
331 current_width += cluster_width;
332 }
333
334 if !current.is_empty() {
335 out.push(current);
336 }
337 out
338 }
339
340 /// Word wrap by display width so the composed row count is exact and no
341 /// paragraph re-wrap can clip a locale with longer sentences.
342 pub(crate) fn wrap_words(text: &str, width: usize) -> Vec<String> {
343 use unicode_width::UnicodeWidthStr;
344 let width = width.max(8);
345 let mut out = Vec::new();
346 let mut current = String::new();
347 let mut current_width = 0usize;
348 for word in text.split_whitespace() {
349 let word_width = UnicodeWidthStr::width(word);
350
351 // A token wider than the whole lane cannot fit on any line. Scripts
352 // that do not delimit words produce exactly one such token per
353 // sentence, and the word-only path below never breaks it — it appended
354 // the token whole and the terminal clipped the tail, silently dropping
355 // the second half of every long Japanese string.
356 if word_width > width {
357 if !current.is_empty() {
358 out.push(std::mem::take(&mut current));
359 current_width = 0;
360 }
361 let mut chunks = break_by_display_width(word, width);
362 if let Some(last) = chunks.pop() {
363 out.extend(chunks);
364 current_width = UnicodeWidthStr::width(last.as_str());
365 current = last;
366 }
367 continue;
368 }
369
370 let needed = if current.is_empty() {
371 word_width
372 } else {
373 current_width + 1 + word_width
374 };
375 if !current.is_empty() && needed > width {
376 out.push(std::mem::take(&mut current));
377 current_width = 0;
378 }
379 if !current.is_empty() {
380 current.push(' ');
381 current_width += 1;
382 }
383 current.push_str(word);
384 current_width += word_width;
385 }
386 if !current.is_empty() {
387 out.push(current);
388 }
389 if out.is_empty() {
390 out.push(String::new());
391 }
392 out
393 }
394
395 pub fn default_marker_path() -> Option<PathBuf> {
396 let primary_home = codewhale_config::codewhale_home().ok()?;
397 let legacy_home = if codewhale_config::codewhale_home_is_explicit() {
398 None
399 } else {
400 codewhale_config::legacy_deepseek_home().ok()
401 };
402 Some(marker_path_with_roots(
403 &primary_home,
404 legacy_home.as_deref(),
405 ))
406 }
407
408 #[cfg(test)]
409 fn marker_path_with_home(home: &Path) -> PathBuf {
410 marker_path_with_roots(
411 &home.join(".codewhale"),
412 Some(home.join(".deepseek").as_path()),
413 )
414 }
415
416 fn marker_path_with_roots(primary_home: &Path, legacy_home: Option<&Path>) -> PathBuf {
417 let primary = primary_home.join(ONBOARDED_MARKER_FILE);
418 if primary.exists() {
419 return primary;
420 }
421 if let Some(legacy_home) = legacy_home {
422 let legacy = legacy_home.join(ONBOARDED_MARKER_FILE);
423 if legacy.exists() {
424 return legacy;
425 }
426 }
427 primary
428 }
429
430 pub fn is_onboarded() -> bool {
431 default_marker_path().is_some_and(|path| path.exists())
432 }
433
434 pub fn mark_onboarded() -> std::io::Result<PathBuf> {
435 let path = default_marker_path().ok_or_else(|| {
436 std::io::Error::new(
437 std::io::ErrorKind::NotFound,
438 "Codewhale home directory not found",
439 )
440 })?;
441 mark_onboarded_at_path(path)
442 }
443
444 #[cfg(test)]
445 fn mark_onboarded_at_home(home: &Path) -> std::io::Result<PathBuf> {
446 let path = marker_path_with_home(home);
447 mark_onboarded_at_path(path)
448 }
449
450 fn mark_onboarded_at_path(path: PathBuf) -> std::io::Result<PathBuf> {
451 if let Some(parent) = path.parent() {
452 std::fs::create_dir_all(parent)?;
453 }
454 codewhale_util::utils::write_atomic(&path, b"")?;
455 Ok(path)
456 }
457
458 pub fn mark_trusted(workspace: &Path) -> anyhow::Result<PathBuf> {
459 codewhale_runtime::config::save_workspace_trust(workspace)
460 }
461
462 /// Whether the UI locale can be trusted without asking. An explicit settings
463 /// value or an environment locale that resolves to a shipped pack is
464 /// confident; anything else defaults to English silently, so first run asks
465 /// once. Returning users never see the language screen.
466 pub fn locale_confidently_inferred(setting: &str) -> bool {
467 let normalized = codewhale_localization::normalize_configured_locale(setting);
468 if normalized.is_some_and(|tag| tag != "auto") {
469 return true;
470 }
471 ["LC_ALL", "LC_MESSAGES", "LANG"].iter().any(|key| {
472 std::env::var(key)
473 .ok()
474 .filter(|value| locale_var_names_a_language(value))
475 .and_then(|value| codewhale_localization::normalize_configured_locale(&value))
476 .is_some_and(|tag| tag != "auto")
477 })
478 }
479
480 /// A POSIX/C locale names an encoding, not a language: `C` and `C.UTF-8`
481 /// pass through `normalize_configured_locale` as concrete tags, so the
482 /// inference gate must reject them explicitly or a stock terminal
483 /// environment reads as a confident language pick.
484 fn locale_var_names_a_language(value: &str) -> bool {
485 let language = value.split(['.', '_', '@']).next().unwrap_or_default();
486 !matches!(language, "" | "C" | "POSIX" | "c" | "posix")
487 }
488
489 /// The example task the ready screen seeds into the composer, chosen from
490 /// what is cheaply visible in the workspace.
491 pub fn first_task_seed(workspace: &Path, locale: codewhale_localization::Locale) -> String {
492 let id = if CODE_PROJECT_MARKERS
493 .iter()
494 .any(|marker| workspace.join(marker).is_file())
495 {
496 MessageId::OnboardSeedCodeProject
497 } else {
498 MessageId::OnboardSeedFolder
499 };
500 codewhale_localization::tr(locale, id).into_owned()
501 }
502
503 /// Welcome → the first decision this run actually needs.
504 pub fn advance_onboarding_from_welcome(app: &mut App) {
505 app.clear_setup_notice();
506 app.onboarding = if app.onboarding_had_language_step {
507 OnboardingState::Language
508 } else if app.onboarding_needs_api_key {
509 OnboardingState::Provider
510 } else if trust_decision_required(app) {
511 OnboardingState::TrustDirectory
512 } else {
513 OnboardingState::Ready
514 };
515 }
516
517 /// Language → the next decision; the language step never repeats.
518 pub fn advance_onboarding_after_language(app: &mut App) {
519 app.clear_setup_notice();
520 app.onboarding = if app.onboarding_needs_api_key {
521 OnboardingState::Provider
522 } else if trust_decision_required(app) {
523 OnboardingState::TrustDirectory
524 } else {
525 OnboardingState::Ready
526 };
527 }
528
529 /// Provider setup → trust when a decision is required, otherwise the ready
530 /// screen. A message already typed skips the ready screen and returns to the
531 /// composer with the draft intact.
532 pub fn advance_onboarding_after_provider(app: &mut App) {
533 app.clear_setup_notice();
534 if trust_decision_required(app) {
535 app.onboarding = OnboardingState::TrustDirectory;
536 } else if !app.composer.input.trim().is_empty() && !app.onboarding_explore_offline {
537 app.finish_onboarding_without_feature_intro();
538 } else {
539 app.onboarding = OnboardingState::Ready;
540 }
541 }
542
543 /// Take the explicit "explore offline" exit advertised by Provider setup
544 /// (#3927).
545 ///
546 /// The contract this encodes, in full:
547 ///
548 /// * **No provider is selected and no route is activated.** This function must
549 /// never reach `switch_provider`, never persist `provider`, and never write a
550 /// credential. Callers pass only `&mut App`, which makes that structural.
551 /// * **No draft secret is owned by `App`.** The caller closes the canonical
552 /// picker before entering this transition, dropping its private draft.
553 /// * **`onboarding_needs_api_key` stays true**, because nothing was supplied.
554 /// The launch surface, `/setup`, and doctor keep telling the truth.
555 /// * **The remaining required decisions still run** — trust, then the ready
556 /// screen — so browsing offline is a complete first run and not an early
557 /// exit.
558 /// * Queue semantics are inherited from `offline_mode`, untouched here.
559 pub fn choose_offline_explore(app: &mut App) {
560 app.api_key_env_only = false;
561 app.onboarding_needs_api_key = true;
562 app.onboarding_explore_offline = true;
563 app.offline_mode = true;
564 // `advance_*` clears the status bar, so the label is applied after it.
565 advance_onboarding_after_provider(app);
566 app.show_onboarding_notice(
567 app.tr(MessageId::OnboardOfflineNotice).into_owned(),
568 super::app::StatusToastLevel::Warning,
569 );
570 app.needs_redraw = true;
571 }
572
573 /// Retire the offline-explore state once a real route is activated (#3927).
574 ///
575 /// This is the *only* thing that retires the label and the offline queueing it
576 /// armed: it is not time-based and not cleared by dismissing a screen. A
577 /// message held while offline is returned to the composer so the person can
578 /// send it on the route that just became active; any further held messages
579 /// stay queued behind it in order and drain after that turn completes.
580 pub fn clear_offline_explore_on_route_activation(app: &mut App) {
581 app.onboarding_explore_offline = false;
582 if app.offline_mode {
583 app.offline_mode = false;
584 app.pop_first_queued_into_draft();
585 app.needs_redraw = true;
586 }
587 }
588
589 /// Finish first run from the ready screen and land in the real composer,
590 /// pre-seeded with a useful first task for this folder. Enter opens the
591 /// product; it never opens another educational surface.
592 pub fn finish_ready_and_open_composer(app: &mut App) {
593 app.finish_onboarding_without_feature_intro();
594 if app.composer.input.trim().is_empty() {
595 let seed = first_task_seed(&app.workspace, app.ui_locale);
596 app.composer.input = seed;
597 app.composer.cursor_position = app.composer.input.chars().count();
598 }
599 app.needs_redraw = true;
600 }
601
602 #[cfg(test)]
603 mod tests {
604 use super::*;
605 use crate::tui::app::{App, TuiOptions};
606 use codewhale_localization::{Locale, MessageId, tr};
607 use codewhale_runtime::config::Config;
608 use std::path::PathBuf;
609
610 /// A first-run app with the onboarding decision reset to "nothing asked
611 /// yet". `App::new` derives that decision from the ambient machine —
612 /// inferable locale, an existing `settings.toml`, a provider key in the
613 /// environment — so a fixture that overrides only the flags it names
614 /// inherits the rest of the developer's box and asserts something
615 /// different in CI. Every test below opts in to the steps it is about.
616 fn test_app_with_locale(locale: Locale) -> App {
617 let options = TuiOptions {
618 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
619 };
620 let mut app = App::new(options, &Config::default());
621 app.ui_locale = locale;
622 app.onboarding_needs_api_key = false;
623 app.onboarding_missing_key_recovery = false;
624 app.onboarding_explore_offline = false;
625 app.onboarding_had_language_step = false;
626 app.onboarding_had_provider_step = false;
627 app.onboarding_had_trust_step = false;
628 app
629 }
630
631 fn flattened(lines: Vec<Line<'static>>) -> String {
632 lines
633 .into_iter()
634 .flat_map(|line| {
635 line.spans
636 .into_iter()
637 .map(|span| span.content.to_string())
638 .collect::<Vec<_>>()
639 })
640 .collect::<Vec<_>>()
641 .join("\n")
642 }
643
644 // ── Navigation: one decision per screen, conditional ─────────────────
645
646 #[test]
647 fn welcome_routes_to_the_first_decision_this_run_needs() {
648 let tmp = tempfile::tempdir().expect("tempdir");
649
650 // Everything configured: welcome → ready with zero questions between.
651 let mut app = test_app_with_locale(Locale::En);
652 app.workspace = tmp.path().to_path_buf();
653 app.trust_mode = true;
654 app.onboarding_needs_api_key = false;
655 app.onboarding_had_language_step = false;
656 advance_onboarding_from_welcome(&mut app);
657 assert_eq!(app.onboarding, OnboardingState::Ready);
658
659 // No route configured: provider comes first.
660 let mut app = test_app_with_locale(Locale::En);
661 app.workspace = tmp.path().to_path_buf();
662 app.trust_mode = true;
663 app.onboarding_needs_api_key = true;
664 advance_onboarding_from_welcome(&mut app);
665 assert_eq!(app.onboarding, OnboardingState::Provider);
666
667 // Route present, workspace untrusted: trust is the only decision.
668 let mut app = test_app_with_locale(Locale::En);
669 app.workspace = tmp.path().to_path_buf();
670 app.trust_mode = false;
671 app.onboarding_needs_api_key = false;
672 advance_onboarding_from_welcome(&mut app);
673 assert_eq!(app.onboarding, OnboardingState::TrustDirectory);
674
675 // Language cannot be inferred: it precedes every other decision.
676 let mut app = test_app_with_locale(Locale::En);
677 app.workspace = tmp.path().to_path_buf();
678 app.trust_mode = false;
679 app.onboarding_needs_api_key = true;
680 app.onboarding_had_language_step = true;
681 advance_onboarding_from_welcome(&mut app);
682 assert_eq!(app.onboarding, OnboardingState::Language);
683 }
684
685 #[test]
686 fn language_step_never_repeats_and_falls_through_to_ready() {
687 let tmp = tempfile::tempdir().expect("tempdir");
688 let mut app = test_app_with_locale(Locale::En);
689 app.workspace = tmp.path().to_path_buf();
690 app.trust_mode = true;
691 app.onboarding_had_language_step = true;
692 app.onboarding_needs_api_key = false;
693
694 advance_onboarding_after_language(&mut app);
695 assert_eq!(app.onboarding, OnboardingState::Ready);
696 }
697
698 #[test]
699 fn provider_step_routes_to_trust_only_when_a_decision_is_required() {
700 let tmp = tempfile::tempdir().expect("tempdir");
701
702 let mut app = test_app_with_locale(Locale::En);
703 app.workspace = tmp.path().to_path_buf();
704 app.trust_mode = false;
705 app.onboarding_missing_key_recovery = false;
706 advance_onboarding_after_provider(&mut app);
707 assert_eq!(app.onboarding, OnboardingState::TrustDirectory);
708
709 let mut trusted = test_app_with_locale(Locale::En);
710 trusted.workspace = tmp.path().to_path_buf();
711 trusted.trust_mode = true;
712 advance_onboarding_after_provider(&mut trusted);
713 assert_eq!(trusted.onboarding, OnboardingState::Ready);
714 }
715
716 #[test]
717 fn missing_key_recovery_ends_on_ready_like_a_first_run() {
718 let mut app = test_app_with_locale(Locale::En);
719 app.trust_mode = true;
720 app.onboarding_missing_key_recovery = true;
721 advance_onboarding_after_provider(&mut app);
722 assert_eq!(app.onboarding, OnboardingState::Ready);
723 }
724
725 #[test]
726 fn explore_offline_still_traverses_trust_then_ready() {
727 let tmp = tempfile::tempdir().expect("tempdir");
728 let mut app = test_app_with_locale(Locale::En);
729 app.onboarding = OnboardingState::Provider;
730 app.trust_mode = false;
731 app.workspace = tmp.path().to_path_buf();
732
733 choose_offline_explore(&mut app);
734 assert_eq!(app.onboarding, OnboardingState::TrustDirectory);
735 assert!(app.onboarding_explore_offline);
736
737 // A trusted workspace skips only the trust screen, never the ending.
738 let mut trusted = test_app_with_locale(Locale::En);
739 trusted.onboarding = OnboardingState::Provider;
740 trusted.trust_mode = true;
741 choose_offline_explore(&mut trusted);
742 assert_eq!(trusted.onboarding, OnboardingState::Ready);
743 }
744
745 #[test]
746 fn offline_explore_selects_no_provider_and_writes_no_credential() {
747 let mut app = test_app_with_locale(Locale::En);
748 app.onboarding = OnboardingState::Provider;
749 app.onboarding_needs_api_key = true;
750 app.trust_mode = true;
751 let provider_before = app.api_provider;
752 let model_before = app.model.clone();
753
754 choose_offline_explore(&mut app);
755
756 assert_eq!(app.api_provider, provider_before);
757 assert_eq!(app.model, model_before);
758 assert!(!app.api_key_env_only);
759 assert!(app.onboarding_needs_api_key);
760 assert!(app.onboarding_explore_offline);
761 assert!(app.offline_mode);
762 }
763
764 #[test]
765 fn offline_label_only_clears_when_a_route_is_activated() {
766 let mut app = test_app_with_locale(Locale::En);
767 app.trust_mode = true;
768 choose_offline_explore(&mut app);
769 assert!(app.onboarding_explore_offline);
770
771 clear_offline_explore_on_route_activation(&mut app);
772 assert!(!app.onboarding_explore_offline);
773 assert!(!app.offline_mode);
774 assert_eq!(
775 app.decide_submit_disposition(),
776 crate::tui::app::SubmitDisposition::Immediate
777 );
778 }
779
780 #[test]
781 fn route_activation_returns_the_held_message_to_the_composer() {
782 let mut app = test_app_with_locale(Locale::En);
783 app.trust_mode = true;
784 choose_offline_explore(&mut app);
785 app.input.clear();
786 app.queue_message(crate::tui::app::QueuedMessage::new(
787 "first task".to_string(),
788 None,
789 ));
790 assert_eq!(
791 app.decide_submit_disposition(),
792 crate::tui::app::SubmitDisposition::Queue
793 );
794
795 clear_offline_explore_on_route_activation(&mut app);
796
797 assert_eq!(app.input, "first task");
798 assert!(app.queued_messages.is_empty());
799 }
800
801 #[test]
802 fn route_activation_keeps_the_oldest_held_message_first() {
803 let mut app = test_app_with_locale(Locale::En);
804 app.trust_mode = true;
805 choose_offline_explore(&mut app);
806 app.input.clear();
807 for text in ["first task", "second task"] {
808 app.queue_message(crate::tui::app::QueuedMessage::new(text.to_string(), None));
809 }
810
811 clear_offline_explore_on_route_activation(&mut app);
812
813 assert_eq!(app.input, "first task");
814 assert_eq!(app.queued_messages.len(), 1);
815 assert_eq!(app.queued_messages[0].display, "second task");
816 }
817
818 // ── Conditional required steps: the counter ──────────────────────────
819
820 #[test]
821 fn progress_counts_only_required_decisions() {
822 let tmp = tempfile::tempdir().expect("tempdir");
823
824 // One required decision → no counter at all.
825 let mut app = test_app_with_locale(Locale::En);
826 app.workspace = tmp.path().to_path_buf();
827 app.trust_mode = true;
828 app.onboarding_needs_api_key = true;
829 app.onboarding = OnboardingState::Provider;
830 assert_eq!(required_progress(&app), None);
831
832 // Language + provider: the language screen is 1 of 2.
833 app.onboarding_had_language_step = true;
834 app.onboarding_had_provider_step = true;
835 app.onboarding = OnboardingState::Language;
836 assert_eq!(required_progress(&app), Some((1, 2)));
837 app.onboarding = OnboardingState::Provider;
838 assert_eq!(required_progress(&app), Some((2, 2)));
839
840 // Completing provider setup changes live route state, but never
841 // rewrites the receipt-backed denominator for this run.
842 app.onboarding_needs_api_key = false;
843 app.onboarding_had_trust_step = true;
844 app.onboarding = OnboardingState::TrustDirectory;
845 assert_eq!(required_progress(&app), Some((3, 3)));
846
847 // Welcome and ready are not decisions and never carry a counter.
848 app.onboarding = OnboardingState::Welcome;
849 assert_eq!(required_progress(&app), None);
850 app.onboarding = OnboardingState::Ready;
851 assert_eq!(required_progress(&app), None);
852 }
853
854 // ── Language inference gate ───────────────────────────────────────────
855
856 #[test]
857 fn language_step_is_required_only_when_the_locale_is_not_inferable() {
858 let _env_lock = crate::test_support::lock_test_env();
859 let _guard = crate::test_support::EnvVarGuard::remove("LC_ALL");
860 let _messages = crate::test_support::EnvVarGuard::remove("LC_MESSAGES");
861 let _lang = crate::test_support::EnvVarGuard::remove("LANG");
862
863 assert!(!locale_confidently_inferred("auto"));
864 assert!(!locale_confidently_inferred(""));
865
866 // An explicit settings pick is always confident.
867 assert!(locale_confidently_inferred("ja"));
868 assert!(locale_confidently_inferred("zh-Hans"));
869
870 // A shipped locale in the environment is confident…
871 let _lang = crate::test_support::EnvVarGuard::set("LANG", "ja_JP.UTF-8");
872 assert!(locale_confidently_inferred("auto"));
873
874 // …but a POSIX/C environment is not a language signal.
875 let _lang = crate::test_support::EnvVarGuard::set("LANG", "C");
876 assert!(!locale_confidently_inferred("auto"));
877 let _lang = crate::test_support::EnvVarGuard::set("LANG", "C.UTF-8");
878 assert!(!locale_confidently_inferred("auto"));
879 }
880
881 // ── The seeded first task ────────────────────────────────────────────
882
883 #[test]
884 fn seed_speaks_to_the_workspace_contents() {
885 let code_dir = tempfile::tempdir().expect("tempdir");
886 std::fs::write(code_dir.path().join("Cargo.toml"), "[package]\n").expect("marker");
887 assert_eq!(
888 first_task_seed(code_dir.path(), Locale::En),
889 tr(Locale::En, MessageId::OnboardSeedCodeProject)
890 );
891
892 let plain_dir = tempfile::tempdir().expect("tempdir");
893 std::fs::write(plain_dir.path().join("README.md"), "notes\n").expect("readme");
894 assert_eq!(
895 first_task_seed(plain_dir.path(), Locale::En),
896 tr(Locale::En, MessageId::OnboardSeedFolder)
897 );
898 }
899
900 #[test]
901 fn finishing_from_ready_seeds_the_composer_and_marks_onboarding_done() {
902 let _env_lock = crate::test_support::lock_test_env();
903 let home = tempfile::tempdir().expect("home");
904 let _home = crate::test_support::EnvVarGuard::set("HOME", home.path());
905 let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", home.path());
906 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
907
908 let workspace = tempfile::tempdir().expect("workspace");
909 std::fs::write(workspace.path().join("package.json"), "{}\n").expect("marker");
910
911 let mut app = test_app_with_locale(Locale::En);
912 app.workspace = workspace.path().to_path_buf();
913 app.onboarding = OnboardingState::Ready;
914
915 finish_ready_and_open_composer(&mut app);
916
917 assert_eq!(app.onboarding, OnboardingState::None);
918 assert!(is_onboarded(), "the ready screen completes first run");
919 assert_eq!(
920 app.composer.input,
921 tr(Locale::En, MessageId::OnboardSeedCodeProject)
922 );
923 assert_eq!(
924 app.composer.cursor_position,
925 app.composer.input.chars().count()
926 );
927 }
928
929 #[test]
930 fn finishing_from_ready_preserves_a_real_cli_prompt() {
931 let _env_lock = crate::test_support::lock_test_env();
932 let home = tempfile::tempdir().expect("home");
933 let _home = crate::test_support::EnvVarGuard::set("HOME", home.path());
934 let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", home.path());
935 let _codewhale_home = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", home.path());
936
937 let mut app = test_app_with_locale(Locale::En);
938 app.onboarding = OnboardingState::Ready;
939 app.composer.input = "Fix the failing build I asked for.".to_string();
940 app.composer.cursor_position = app.composer.input.chars().count();
941
942 finish_ready_and_open_composer(&mut app);
943
944 assert_eq!(app.onboarding, OnboardingState::None);
945 assert_eq!(app.composer.input, "Fix the failing build I asked for.");
946 assert_eq!(
947 app.composer.cursor_position,
948 app.composer.input.chars().count()
949 );
950 }
951
952 // ── Onboarded-state persistence contract ─────────────────────────────
953
954 #[test]
955 fn fresh_install_marker_path_uses_codewhale_not_legacy() {
956 let tmp = tempfile::tempdir().expect("tempdir");
957
958 let expected = tmp.path().join(".codewhale").join(ONBOARDED_MARKER_FILE);
959 assert_eq!(marker_path_with_home(tmp.path()), expected);
960
961 let written = mark_onboarded_at_home(tmp.path()).expect("mark onboarded");
962 assert_eq!(written, expected);
963 assert!(expected.exists());
964 assert!(
965 !tmp.path().join(".deepseek").exists(),
966 "fresh onboarding must not recreate the legacy .deepseek dir"
967 );
968 }
969
970 #[test]
971 fn existing_legacy_marker_is_preserved() {
972 let tmp = tempfile::tempdir().expect("tempdir");
973 let legacy = tmp.path().join(".deepseek").join(ONBOARDED_MARKER_FILE);
974 std::fs::create_dir_all(legacy.parent().expect("legacy parent")).expect("mkdir legacy");
975 std::fs::write(&legacy, "").expect("seed legacy marker");
976
977 assert_eq!(marker_path_with_home(tmp.path()), legacy);
978 assert_eq!(
979 mark_onboarded_at_home(tmp.path()).expect("mark onboarded"),
980 legacy
981 );
982 }
983
984 #[test]
985 fn codewhale_marker_wins_over_legacy_marker() {
986 let tmp = tempfile::tempdir().expect("tempdir");
987 let primary = tmp.path().join(".codewhale").join(ONBOARDED_MARKER_FILE);
988 let legacy = tmp.path().join(".deepseek").join(ONBOARDED_MARKER_FILE);
989 for marker in [&primary, &legacy] {
990 std::fs::create_dir_all(marker.parent().expect("marker parent")).expect("mkdir");
991 std::fs::write(marker, "").expect("seed marker");
992 }
993
994 assert_eq!(marker_path_with_home(tmp.path()), primary);
995 }
996
997 #[test]
998 fn explicit_codewhale_home_marker_survives_restart_resolution() {
999 let _env_lock = crate::test_support::lock_test_env();
1000 let tmp = tempfile::tempdir().expect("tempdir");
1001 let ambient_home = tmp.path().join("ambient profile");
1002 let isolated_home = tmp.path().join("isolated Codewhale state");
1003 let ambient_legacy = ambient_home.join(".deepseek").join(ONBOARDED_MARKER_FILE);
1004 std::fs::create_dir_all(ambient_legacy.parent().expect("legacy parent")).expect("mkdir");
1005 std::fs::write(&ambient_legacy, "").expect("seed ambient legacy marker");
1006 let _home = crate::test_support::EnvVarGuard::set("HOME", &ambient_home);
1007 let _userprofile = crate::test_support::EnvVarGuard::set("USERPROFILE", &ambient_home);
1008 let _codewhale_home =
1009 crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", &isolated_home);
1010
1011 let expected = isolated_home.join(ONBOARDED_MARKER_FILE);
1012 assert_eq!(default_marker_path().as_deref(), Some(expected.as_path()));
1013 assert!(!is_onboarded());
1014
1015 let written = mark_onboarded().expect("mark onboarded");
1016
1017 assert_eq!(written, expected);
1018 assert!(is_onboarded());
1019 assert_eq!(default_marker_path().as_deref(), Some(expected.as_path()));
1020 assert!(ambient_legacy.exists(), "legacy marker remains untouched");
1021 assert!(
1022 !ambient_home.join(".codewhale").exists(),
1023 "an explicit state root must not write into the ambient profile"
1024 );
1025 }
1026
1027 // ── Locale completeness for the new copy ─────────────────────────────
1028
1029 #[test]
1030 fn calm_onboarding_copy_is_translated_in_every_complete_pack() {
1031 for locale in Locale::shipped_complete() {
1032 for id in [
1033 MessageId::OnboardWelcomeTitle,
1034 MessageId::OnboardWelcomeLead,
1035 MessageId::OnboardWelcomeBegin,
1036 MessageId::OnboardActionBack,
1037 MessageId::OnboardActionExit,
1038 MessageId::OnboardStepsTitle,
1039 MessageId::OnboardLanguagePick,
1040 MessageId::OnboardLanguageKeep,
1041 MessageId::OnboardProviderChoose,
1042 MessageId::OnboardProviderOffline,
1043 MessageId::OnboardTrustActionTrust,
1044 MessageId::OnboardTrustActionSkip,
1045 MessageId::OnboardTrustActionQuit,
1046 MessageId::OnboardReadyTitle,
1047 MessageId::OnboardReadyLead,
1048 MessageId::OnboardReadyStart,
1049 MessageId::OnboardReadyCustomize,
1050 MessageId::CmdRemoteControlDescription,
1051 MessageId::OnboardSeedCodeProject,
1052 MessageId::OnboardSeedFolder,
1053 ] {
1054 let text = tr(*locale, id);
1055 assert!(!text.is_empty(), "{locale:?} {id:?} is empty");
1056 if *locale != Locale::En {
1057 assert_ne!(
1058 text,
1059 tr(Locale::En, id),
1060 "{locale:?} {id:?} silently fell back to English"
1061 );
1062 }
1063 }
1064 }
1065 }
1066
1067 #[test]
1068 fn ready_screen_advertises_only_keys_it_handles() {
1069 use crate::tui::views::action_footer_lines;
1070
1071 let mut app = test_app_with_locale(Locale::En);
1072 app.onboarding = OnboardingState::Ready;
1073 let rail = flattened(action_footer_lines(&action_hints(&app), 80));
1074 assert!(rail.contains("Enter"), "{rail}");
1075 assert!(rail.contains("change the look"), "{rail}");
1076 assert!(
1077 !rail.contains("/rc"),
1078 "the Ready screen owns the keyboard, so /rc cannot be typed: {rail}"
1079 );
1080 }
1081
1082 #[test]
1083 fn provider_screen_advertises_the_offline_choice() {
1084 use crate::tui::views::action_footer_lines;
1085
1086 let mut app = test_app_with_locale(Locale::En);
1087 app.onboarding = OnboardingState::Provider;
1088 let rail = flattened(action_footer_lines(&action_hints(&app), 70));
1089 assert!(rail.contains("Enter"), "primary choice first: {rail}");
1090 assert!(
1091 rail.contains("Ctrl+O"),
1092 "offline exit must be advertised: {rail}"
1093 );
1094 assert!(
1095 rail.contains(tr(Locale::En, MessageId::OnboardProviderOffline).as_ref()),
1096 "offline exit needs its translated label: {rail}"
1097 );
1098 }
1099
1100 #[test]
1101 fn wrap_words_breaks_scripts_that_have_no_spaces() {
1102 use unicode_width::UnicodeWidthStr;
1103 // The real ja provider blurb. `split_whitespace` yields one token, so
1104 // the word-only wrapper emitted a single 110-column line and an 80-column
1105 // terminal clipped everything after "ローカ" — the half of the sentence
1106 // that tells the user local runtimes need no key.
1107 let ja = "モデルの実行先を選びます。ホステッドプロバイダーにはキーが必要ですが、ローカルランタイムはキーなしで続行できます。";
1108 assert!(
1109 ja.split_whitespace().count() == 1,
1110 "fixture must be a single whitespace-delimited token"
1111 );
1112
1113 let lines = wrap_words(ja, 76);
1114 assert!(
1115 lines.len() > 1,
1116 "space-less text must wrap, not clip: {lines:?}"
1117 );
1118 for line in &lines {
1119 assert!(
1120 UnicodeWidthStr::width(line.as_str()) <= 76,
1121 "line exceeds the lane: {:?} ({} cols)",
1122 line,
1123 UnicodeWidthStr::width(line.as_str())
1124 );
1125 }
1126 // Nothing may be dropped: the rejoined lines must reproduce the source.
1127 assert_eq!(lines.concat(), ja, "wrapping must not lose characters");
1128 }
1129
1130 #[test]
1131 fn wrap_words_keeps_latin_wrapping_unchanged() {
1132 let text = "Pick where your model runs. Hosted providers need a key; local runtimes can continue without one.";
1133 let lines = wrap_words(text, 60);
1134 assert!(lines.len() >= 2);
1135 for line in &lines {
1136 assert!(line.len() <= 60, "{line:?}");
1137 assert!(!line.starts_with(' ') && !line.ends_with(' '), "{line:?}");
1138 }
1139 assert_eq!(lines.join(" "), text, "word wrapping must round-trip");
1140 }
1141
1142 #[test]
1143 fn wrap_words_does_not_open_a_line_with_japanese_closing_punctuation() {
1144 // Kinsoku: 。、」) and friends may not begin a line.
1145 let text = "あいうえおかきくけこさしすせそたちつてと。";
1146 for width in 4..=20 {
1147 for line in wrap_words(text, width) {
1148 let first = line.chars().next().unwrap();
1149 assert!(
1150 !NO_LINE_START.contains(&first),
1151 "width {width}: line starts with {first:?} in {line:?}"
1152 );
1153 }
1154 }
1155 }
1156
1157 #[test]
1158 fn wrap_words_handles_mixed_latin_and_cjk() {
1159 let text = "Codewhale はこのフォルダーで一緒に作業します。";
1160 let lines = wrap_words(text, 20);
1161 assert_eq!(
1162 lines.join("").replace(' ', ""),
1163 text.replace(' ', ""),
1164 "mixed-script text must not lose characters: {lines:?}"
1165 );
1166 }
1167 }
1168
1168 lines RUST