diff --git a/CLAUDE.md b/CLAUDE.md index 9e5051f..8e8b967 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,9 +16,9 @@ Claudiu is a native Rust + GPUI desktop app that manages sessions around the use GitHub issues hold intent, one issue per feature with a checklist in its body; the code and the maintainer decide what is true. Check off items the code already does. Add entries for requests that aren't listed, and for problems you notice outside the task, rather than fixing those in passing, so every diff stays reviewable. Order is a suggestion: if a request seems to depend on unfinished work, say so in one line and continue. -Care about the project's long-term health, not just the request in front of you. When a request would harm it, say so plainly and early, give your own recommendation, and don't agree just to be agreeable. Hold your position if the pushback brings no new information. Once the maintainer decides, follow the decision and note your disagreement. +Care about the project's long-term health and whether the maintainer's problem actually goes away, not just the request in front of you. Suggest what they haven't asked for but will need. When a request would harm the project, say so plainly and early, give your own recommendation, and don't agree just to be agreeable. Hold your position if the pushback brings no new information. Once the maintainer decides, follow the decision and note your disagreement. -Ask the maintainer about product direction, scope, and anything irreversible or outward-facing, such as pushing, deleting data, adding a dependency or closing issues, unless the settings above allow it. Ask through the harness's structured question tool when it has one, recommended option first; otherwise ask one question per message with numbered options. Decide everything reversible yourself and report it. Ask a question only when you can't continue without a decision. Finishing a change is not such a point: report it in a line or two and stop, and leave committing and pushing to the settings or the maintainer's word. +Ask the maintainer about product direction, scope, and anything irreversible or outward-facing, such as pushing, deleting data, adding a dependency or closing issues, unless the settings above allow it. Ask through the harness's structured question tool when it has one, recommended option first; otherwise ask one question per message with numbered options. The maintainer is the source of truth and decides everything; don't guess. Every real choice, including scope, behavior, wording and design, goes to them with your recommendation and the reason, and so does anything they'd want to know, such as a gap or a better approach, when you find it. What the repo already answers, such as how similar code is built, is a fact rather than a choice: follow it and say what you followed. Finishing a change is not such a point: report it in a line or two and stop, and leave committing and pushing to the settings or the maintainer's word. The maintainer can override any setting for a single request, for example "go autonomous, commit and push everything" or "ask before each commit"; the override lasts until that request is done. @@ -32,9 +32,9 @@ Work inline; spawn subagents only as the settings allow, except the plan review People who don't use agents read and maintain this code, so aim for code that is obviously correct to a newcomer. Rank choices by correctness, then how easily the code reads and tests, then size; a one-liner that needs decoding is not simple. -Build only what was asked: features, options and configuration nobody requested wait until someone needs them. How the requested thing is built is open. For non-trivial logic, weigh more than one shape and pick the one whose correctness is most obvious, even if it is unconventional. Before writing new code, look for it in this repo, then the standard library and platform, then installed dependencies. +Build only what was asked: features, options and configuration nobody requested wait until someone needs them. New code takes the shape of the existing code that does something similar: its file layout, naming, error handling, state, UI and tests, and its helpers rather than new ones. When that shape doesn't fit, or more than one design is reasonable, recommend the one whose correctness is most obvious and ask. Before writing new code, look for it in this repo, then the standard library and platform, then installed dependencies. -Before editing, find every place the change must reach (callers, tests, fixtures, config, exports) and finish all of them. When a better structure would make the task simpler, use it in this change; when it is bigger than the task, do the task and add the redesign to the tracker with a one-line reason. Keep validation of untrusted input, error handling that prevents data loss, security and accessibility, including in code you move. +Before editing, find every place the change must reach (callers, tests, fixtures, config, exports) and finish all of them. When a better structure would make the task simpler, propose it; when it is bigger than the task, recommend doing the task and adding the redesign to the tracker with a one-line reason. Keep validation of untrusted input, error handling that prevents data loss, security and accessibility, including in code you move. Comments explain why something non-obvious is true, such as a known limit and when it will matter. When code needs a comment to say what it does, rename or restructure it instead. Leave existing comments in code you don't change. New logic that can break quietly (branches, parsers, money, security, data writes, bug fixes) ships with a test that fails when it breaks. diff --git a/Cargo.toml b/Cargo.toml index 48eaf41..e98c511 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -62,7 +62,7 @@ strip = true [target."cfg(windows)".dependencies] junction = "2.1.0" -windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging", "Win32_Foundation", "Win32_Security", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_Threading"] } +windows-sys = { version = "0.61", features = ["Win32_UI_WindowsAndMessaging", "Win32_Foundation", "Win32_Security", "Win32_System_DataExchange", "Win32_System_Memory", "Win32_System_Registry", "Win32_System_Threading"] } [target.'cfg(unix)'.dependencies] libc = "0.2" diff --git a/README.md b/README.md index 353923c..bbceb63 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Claudiu is a native desktop app, written in Rust with [GPUI](https://gpui.rs), t ## What it does -Each session is your own `claude` process in a real pseudo-terminal, so Claude Code's keys, mouse and paste work unchanged. Claudiu has no API keys and never calls the Anthropic API. Sign-in stays with Claude Code. A sidebar lists your projects and sessions. Ended sessions resume through `claude --resume`, and sessions that were running come back at the next start. +Each session is your own `claude` process in a real pseudo-terminal, so Claude Code's keys, mouse and paste work unchanged. Claudiu has no API keys and never calls the Anthropic API. Sign-in stays with Claude Code. The first launch opens a setup window that checks for `claude` (required) and `gh` (optional), links to their install pages and installs nothing. Settings has a Check setup button to open it again. A sidebar lists your projects and sessions. Ended sessions resume through `claude --resume`, and sessions that were running come back at the next start. Around the terminal, Claudiu adds an editor mode (Ctrl+Shift+E) with files, tabs, search, Git change marks and language-server diagnostics, definitions and completion. It also adds usage and context meters, a GitHub pane for issues and pull requests through your `gh` login, defaults for the model, effort and permission mode of new sessions, and extra Claude accounts that share one configuration. Settings lists the rest. diff --git a/src/app/github_pane.rs b/src/app/github_pane.rs index 0ad6453..65c8088 100644 --- a/src/app/github_pane.rs +++ b/src/app/github_pane.rs @@ -88,26 +88,29 @@ impl Workspace { cx, ); } - GhEvent::SignIn => { - let Some(exe) = crate::github::cli::locate() else { return }; - let home = platform::home_dir().unwrap_or_else(|| PathBuf::from(".")); - let spec = SpawnSpec { program: exe.to_string_lossy().into_owned(), args: vec!["auth".into(), "login".into()], cwd: Some(home.clone()), ..Default::default() }; - let record = SessionRecord { - id: new_id(), - kind: SessionKind::Shell, - title: "GitHub sign in".into(), - custom_title: None, - auto_title: None, - project_id: None, - cwd: home, - created_at: now(), - last_active: now(), - exit_code: None, - hidden: false, - claude: None, - }; - self.start(record, spec, true, window, cx); - } + GhEvent::SignIn => self.sign_in_to_github(window, cx), } } + + /// `gh auth login` in a terminal tab. + pub(super) fn sign_in_to_github(&mut self, window: &mut Window, cx: &mut Context) { + let Some(exe) = crate::github::cli::locate() else { return }; + let home = platform::home_dir().unwrap_or_else(|| PathBuf::from(".")); + let spec = SpawnSpec { program: exe.to_string_lossy().into_owned(), args: vec!["auth".into(), "login".into()], cwd: Some(home.clone()), ..Default::default() }; + let record = SessionRecord { + id: new_id(), + kind: SessionKind::Shell, + title: "GitHub sign in".into(), + custom_title: None, + auto_title: None, + project_id: None, + cwd: home, + created_at: now(), + last_active: now(), + exit_code: None, + hidden: false, + claude: None, + }; + self.start(record, spec, true, window, cx); + } } diff --git a/src/app/headless.rs b/src/app/headless.rs index 1b71ecf..6150b5b 100644 --- a/src/app/headless.rs +++ b/src/app/headless.rs @@ -1220,3 +1220,34 @@ fn the_session_list_draws_rows_where_scrolling_brings_them() { let after = row_under_pointer(&mut cx); assert!(after > before + 20, "row {before} before scrolling, {after} after"); } + +/// With no `claude` found, starting a session says so and offers the setup window; asking for it twice shows one. +#[test] +#[ignore] +fn a_missing_claude_offers_the_setup_window() { + let data = tempfile::tempdir().unwrap(); + unsafe { std::env::set_var("CLAUDIU_DATA_DIR", data.path()) }; + let work = tempfile::tempdir().unwrap(); + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let (window, ws) = cx.update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| Workspace::new(window, vec![], cx)))).unwrap(); + + cx.update_window(window, |_, window, app| { + ws.update(app, |ws, cx| { + ws.claude_exe = None; + ws.new_claude(work.path().to_path_buf(), window, cx); + }) + }) + .unwrap(); + let action = ws.read_with(&cx, |ws, _| ws.toast.as_ref().and_then(|t| t.action.as_ref().map(|(label, act)| (label.clone(), matches!(act, Act::OpenSetup))))); + assert_eq!(action, Some(("Check setup".to_string(), true)), "the toast offers the setup window"); + + for _ in 0..2 { + cx.update_window(window, |_, window, app| ws.update(app, |ws, cx| ws.act(Act::OpenSetup, window, cx))).unwrap(); + cx.run_until_parked(); + } + assert_eq!(cx.update(|app| app.windows().len()), 2, "the workspace and one setup window"); +} diff --git a/src/app/mod.rs b/src/app/mod.rs index b13737f..971fcc1 100644 --- a/src/app/mod.rs +++ b/src/app/mod.rs @@ -55,6 +55,7 @@ mod repo; mod selection_reference; mod sessions; mod settings; +mod setup; mod titles; mod visuals; @@ -64,6 +65,7 @@ pub use lifecycle::saved_window_bounds; pub use editor_mode::EditorCommand; pub use file_ops::NameFor; pub use settings::SettingsPage; +pub use setup::{Mode as SetupMode, SetupEvent, SetupView, window_options as setup_window_options}; actions!( claudiu, @@ -129,6 +131,8 @@ pub enum Act { OpenEditor(Editor, PathBuf), ImportProject, OpenSettings, + /// The setup window again, from Settings or the missing-`claude` toast (see `setup.rs`). + OpenSetup, /// A choice in the Settings dialog's effort or permission-mode picker (None = Claude Code's default); kept in the /// dialog until Save. PickEffort(Option), @@ -459,6 +463,8 @@ pub struct Workspace { pub git_busy: Option, /// What Commit & Push would do in the shown session's folder, as last read; `None` until it has been. pub pending: Option<(PathBuf, crate::git::commit::Pending)>, + /// The setup window while it is open, so a second request shows it instead of opening another. + setup_window: Option, } impl Workspace { @@ -554,6 +560,7 @@ impl Workspace { activity: HashMap::new(), git_busy: None, pending: None, + setup_window: None, store, }; // Everything from a previous run is history until clicked. Keep the highlight only if it still exists. @@ -692,6 +699,7 @@ impl Workspace { } } } + Act::OpenSetup => self.open_setup(window, cx), Act::OpenSettings => { let s = &self.store.data.settings; let (shell_t, claude_t) = ( diff --git a/src/app/sessions.rs b/src/app/sessions.rs index 035cf1b..1292d59 100644 --- a/src/app/sessions.rs +++ b/src/app/sessions.rs @@ -108,7 +108,7 @@ impl Workspace { /// `--allowedTools` / `--mcp-config` flags, or they would swallow it. pub(super) fn new_claude_with(&mut self, cwd: PathBuf, mut leading: Vec, by: Starter, window: &mut Window, cx: &mut Context) { let Some(exe) = self.claude_exe.clone() else { - self.toast("Could not find the `claude` CLI. Install Claude Code, or set its path in Settings.", true, cx); + self.show_toast("Could not find the `claude` CLI. Install Claude Code, or set its path in Settings.".into(), true, Some(("Check setup".into(), Act::OpenSetup)), cx); return; }; let session_id = new_id(); diff --git a/src/app/setup.rs b/src/app/setup.rs new file mode 100644 index 0000000..4166a64 --- /dev/null +++ b/src/app/setup.rs @@ -0,0 +1,467 @@ +//! The setup window: a short checklist of the two tools Claudiu runs (`claude`, required; `gh`, optional). It opens +//! alone on a first launch (see `main.rs`) and again from Settings or the missing-`claude` toast. It installs nothing. +//! It never owns the store: it hands the path the user typed back in `SetupEvent::Done`, and the main window applies it. + +use super::*; + +use gpui::{ + Bounds, ClickEvent, EventEmitter, IntoElement, ParentElement, Render, SharedString, StatefulInteractiveElement, Styled, TitlebarOptions, + WindowBounds, WindowOptions, div, prelude::FluentBuilder, px, size, +}; +use gpui_kit::assets::IconName; +use gpui_kit::component::input::Input; + +use crate::github::cli::AuthState; +use crate::panels::theme::{self, hsla}; +use crate::panels::widgets::{button, button_disabled, clawd, icon, section_label, spinner}; + +const CLAUDE_INSTALL_PAGE: &str = "https://code.claude.com/docs/en/setup"; +const GH_INSTALL_PAGE: &str = "https://cli.github.com"; + +/// Said after Check again when a tool is still missing. Every check reads the PATH again (`platform::reload_path`), +/// so what is left is the install itself. +const STILL_MISSING: &str = "Still not found? Finish the install, then press Check again."; + +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub enum Mode { + /// Nothing exists yet: Continue is off until `claude` is found, and closing the window quits. + FirstLaunch, + /// Opened from the running app: Close always works. + Reopened, +} + +pub enum SetupEvent { + /// The user is done. Holds the `claude` path they gave, `None` for "find it yourself". + Done(Option), + /// Run `gh auth login` in a terminal tab of the main window (only sent in `Mode::Reopened`). + SignIn, +} + +pub fn window_options(cx: &App) -> WindowOptions { + let window = size(px(560.0), px(620.0)); + WindowOptions { + window_bounds: Some(WindowBounds::Windowed(Bounds::centered(None, window, cx))), + window_min_size: Some(window), + is_resizable: false, + titlebar: Some(TitlebarOptions { title: Some("Set up Claudiu".into()), ..Default::default() }), + ..Default::default() + } +} + +/// What the user typed for the `claude` path: empty means "find it yourself", anything else must be a file or a +/// program on PATH (the same rule as Settings). +pub fn parse_path(text: &str) -> Result, String> { + let text = text.trim().trim_matches('"'); + if text.is_empty() { + return Ok(None); + } + platform::resolve_program(text).map(Some).ok_or_else(|| format!("“{text}” is not a file or a program on PATH")) +} + +struct Checked { + claude: Option, + gh: AuthState, +} + +pub struct SetupView { + mode: Mode, + path_input: Entity, + /// The path the last check used. + configured: Option, + path_error: Option, + /// `None` while the tools are being looked for. + checked: Option, + /// Check again was pressed, so a tool that is still missing may be waiting for its install to finish. + asked_again: bool, + /// Counts the checks, so the answer of an older `gh` call cannot overwrite a newer one. + checks: u64, + /// Reads the PATH again before each check; `platform::reload_path`, except in tests. + reload_path: fn(), + done: bool, +} + +impl EventEmitter for SetupView {} + +impl SetupView { + pub fn new(mode: Mode, current: Option, window: &mut Window, cx: &mut Context) -> Self { + Self::with_reload(mode, current, platform::reload_path, window, cx) + } + + fn with_reload(mode: Mode, current: Option, reload_path: fn(), window: &mut Window, cx: &mut Context) -> Self { + let text = current.as_ref().map(|p| p.to_string_lossy().into_owned()).unwrap_or_default(); + let path_input = cx.new(|cx| InputState::new(window, cx).default_value(text).placeholder("Found automatically")); + cx.subscribe(&path_input, |view: &mut Self, _, ev: &InputEvent, cx| { + if matches!(ev, InputEvent::PressEnter { .. }) { + view.check_again(cx); + } + }) + .detach(); + if mode == Mode::Reopened { + // The X gives the path back like Close does, which then closes the window itself. On a first launch it just + // closes, which quits the app. + let view = cx.entity().downgrade(); + window.on_window_should_close(cx, move |window, cx| { + // A view that is already gone has nothing to hand back, so the window may just close. + view.update(cx, |view, cx| view.close(window, cx)).is_err() + }); + } + let mut view = Self { mode, path_input, configured: current, path_error: None, checked: None, asked_again: false, checks: 0, reload_path, done: false }; + view.run_checks(cx); + view + } + + /// Look for both tools off the UI thread, after reading the PATH again: a Finder-launched macOS app starts with a + /// minimal one, and a tool installed since Claudiu started is not on any. + fn run_checks(&mut self, cx: &mut Context) { + self.checked = None; + self.checks += 1; + let check = self.checks; + let configured = self.configured.clone(); + let reload_path = self.reload_path; + cx.spawn(async move |this, cx| { + let found = cx + .background_executor() + .spawn(async move { + reload_path(); + Checked { claude: claude::discover(configured.as_deref()), gh: crate::github::cli::check_auth() } + }) + .await; + let _ = this.update(cx, |view, cx| { + if view.checks == check { + view.checked = Some(found); + cx.notify(); + } + }); + }) + .detach(); + cx.notify(); + } + + fn check_again(&mut self, cx: &mut Context) { + match parse_path(self.path_input.read(cx).value().as_ref()) { + Ok(path) => (self.configured, self.path_error) = (path, None), + Err(message) => self.path_error = Some(message), + } + self.asked_again = true; + self.run_checks(cx); + } + + /// The path to give back: what the field says now, or the last good one when the field holds something unusable. + fn path_to_hand_back(&self, cx: &App) -> Option { + parse_path(self.path_input.read(cx).value().as_ref()).unwrap_or_else(|_| self.configured.clone()) + } + + fn finish(&mut self, cx: &mut Context) { + if self.done { + return; + } + self.done = true; + cx.emit(SetupEvent::Done(self.path_to_hand_back(cx))); + } + + /// Hand the path back and close the window. The window goes in a deferred step: the main window listens through a + /// subscription only, and a view dropped before its queued event is delivered takes the event with it. + fn close(&mut self, window: &Window, cx: &mut Context) { + self.finish(cx); + cx.defer_in(window, |_, window, _| window.remove_window()); + } + + fn can_continue(&self) -> bool { + self.mode == Mode::Reopened || self.checked.as_ref().is_some_and(|found| found.claude.is_some()) + } + + fn needs_restart_hint(&self) -> bool { + self.asked_again && self.checked.as_ref().is_some_and(|found| found.claude.is_none() || found.gh == AuthState::Missing) + } +} + +fn card() -> gpui::Div { + div().flex().flex_col().gap(px(10.0)).p(px(14.0)).rounded(px(8.0)).bg(hsla(0x111111)).border_1().border_color(hsla(0x242424)) +} + +fn status_line(glyph: IconName, color: u32, text: impl Into) -> gpui::Div { + div() + .flex() + .items_center() + .gap(px(8.0)) + .text_size(crate::panels::scale::px(13.0)) + .child(div().flex_none().text_color(hsla(color)).child(icon(glyph, 15.0))) + .child(div().min_w_0().child(text.into())) +} + +fn checking_line(id: &'static str) -> gpui::Div { + div() + .flex() + .items_center() + .gap(px(8.0)) + .text_size(crate::panels::scale::px(13.0)) + .text_color(hsla(theme::TEXT_DIM)) + .child(spinner(id, 15.0)) + .child("Checking…") +} + +fn faint(text: impl Into) -> gpui::Div { + div().text_size(crate::panels::scale::px(11.5)).text_color(hsla(theme::TEXT_FAINT)).child(text.into()) +} + +fn tool_title(name: &'static str, tag: &'static str) -> gpui::Div { + div() + .flex() + .items_center() + .gap(px(8.0)) + .child(div().text_size(crate::panels::scale::px(14.0)).font_weight(gpui::FontWeight::SEMIBOLD).child(name)) + .child(section_label(tag)) +} + +impl SetupView { + fn open_page(id: &'static str, label: &'static str, url: &'static str, cx: &mut Context) -> impl IntoElement { + button(id, label, true).on_click(cx.listener(move |_, _: &ClickEvent, _, cx| cx.open_url(url))) + } + + fn claude_row(&self, cx: &mut Context) -> impl IntoElement { + let found = self.checked.as_ref().map(|found| &found.claude); + let state = match found { + None => checking_line("setup-claude-spin"), + Some(Some(path)) => status_line(IconName::CircleCheck, theme::OK, format!("Found at {}", path.display())), + Some(None) => status_line(IconName::CircleX, theme::DANGER, "Not found. Claudiu cannot start sessions without it."), + }; + card() + .child(tool_title("Claude Code", "REQUIRED")) + .child(state) + .when(found == Some(&None), |row| row.child(div().flex().child(Self::open_page("setup-get-claude", "Get Claude Code", CLAUDE_INSTALL_PAGE, cx)))) + .child( + div() + .flex() + .flex_col() + .gap(px(4.0)) + .child(section_label("PATH TO CLAUDE (ONLY IF IT IS SOMEWHERE UNUSUAL)")) + .child(Input::new(&self.path_input)) + .children(self.path_error.clone().map(|message| div().text_size(crate::panels::scale::px(12.0)).text_color(hsla(theme::DANGER)).child(message))), + ) + } + + fn gh_row(&self, cx: &mut Context) -> impl IntoElement { + let (state, action) = match self.checked.as_ref().map(|found| &found.gh) { + None => (checking_line("setup-gh-spin"), None), + Some(AuthState::Ready) => (status_line(IconName::CircleCheck, theme::OK, "Installed and signed in"), None), + Some(AuthState::Missing) => ( + status_line(IconName::CircleSlash, theme::TEXT_DIM, "Not found. Only the GitHub pane needs it."), + Some(Self::open_page("setup-get-gh", "Get GitHub CLI", GH_INSTALL_PAGE, cx).into_any_element()), + ), + Some(AuthState::SignedOut) => { + let sign_in = match self.mode { + Mode::Reopened => button("setup-gh-sign-in", "Sign in with gh", true).on_click(cx.listener(|_, _: &ClickEvent, _, cx| cx.emit(SetupEvent::SignIn))).into_any_element(), + Mode::FirstLaunch => div() + .flex() + .items_center() + .gap(px(10.0)) + .child(button_disabled("setup-gh-sign-in", "Sign in with gh")) + .child(faint("Sign in from the GitHub pane after you continue.")) + .into_any_element(), + }; + (status_line(IconName::CircleX, theme::WARN, "Installed, but not signed in."), Some(sign_in)) + } + Some(AuthState::Unknown(message)) => { + let first_line = message.lines().next().unwrap_or_default().to_string(); + (status_line(IconName::CircleX, theme::WARN, format!("Could not check: {first_line}")), None) + } + }; + card().child(tool_title("GitHub CLI", "OPTIONAL")).child(state).children(action.map(|a| div().flex().child(a))) + } +} + +impl Render for SetupView { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let primary = if self.mode == Mode::Reopened { + button("setup-done", "Close", true).on_click(cx.listener(|view, _: &ClickEvent, window, cx| view.close(window, cx))) + } else if self.can_continue() { + button("setup-done", "Continue", true).on_click(cx.listener(|view, _: &ClickEvent, _, cx| view.finish(cx))) + } else { + button_disabled("setup-done", "Continue") + }; + div() + .size_full() + .flex() + .flex_col() + .gap(px(14.0)) + .p(px(28.0)) + .bg(hsla(theme::APP_BG)) + .text_color(hsla(theme::TEXT)) + .child( + div() + .flex() + .flex_col() + .gap(px(8.0)) + .child(clawd(40.0)) + .child(div().text_size(crate::panels::scale::px(20.0)).font_weight(gpui::FontWeight::SEMIBOLD).child("Set up Claudiu")) + .child( + div() + .text_size(crate::panels::scale::px(13.0)) + .text_color(hsla(theme::TEXT_DIM)) + .child("Claudiu runs your own claude and reaches GitHub through your own gh. It installs nothing; this page only checks that they are there."), + ), + ) + .child(self.claude_row(cx)) + .child(self.gh_row(cx)) + .children(self.needs_restart_hint().then(|| faint(STILL_MISSING))) + .child(div().flex_1()) + .child( + div() + .flex() + .justify_end() + .gap(px(8.0)) + .child(button("setup-check", "Check again", false).on_click(cx.listener(|view, _: &ClickEvent, _, cx| view.check_again(cx)))) + .child(primary), + ) + } +} + +impl Workspace { + /// Show the setup window, or bring it forward when it is already open. + pub(super) fn open_setup(&mut self, window: &mut Window, cx: &mut Context) { + // Settings' unsaved fields go with the dialog; the setup window edits the same `claude` path. + self.modal = None; + self.focus_active(window, cx); + if let Some(open) = self.setup_window + && open.update(cx, |_, window, _| window.activate_window()).is_ok() + { + return; + } + let current = self.store.data.settings.claude_path.clone(); + let opened = gpui_kit::open_window(window_options(cx), cx, |window, cx| cx.new(|cx| SetupView::new(Mode::Reopened, current, window, cx))); + let Ok((handle, view)) = opened else { + self.toast("Could not open the setup window.", true, cx); + return; + }; + self.setup_window = Some(handle); + cx.subscribe_in(&view, window, |ws: &mut Workspace, _, ev: &SetupEvent, window, cx| match ev { + SetupEvent::Done(path) => { + ws.setup_window = None; + ws.apply_setup(path.clone(), cx); + } + SetupEvent::SignIn => { + window.activate_window(); + ws.sign_in_to_github(window, cx); + } + }) + .detach(); + } + + /// Use what the setup window ended with: its `claude` path (`None` clears it), looked for again, and saved. On a + /// first launch the save also creates the state file. + pub fn apply_setup(&mut self, claude_path: Option, cx: &mut Context) { + self.store.data.settings.claude_path = claude_path; + self.claude_exe = claude::discover(self.store.data.settings.claude_path.as_deref()); + self.store.mark_dirty(); + self.store.save(); + cx.notify(); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::TestAppContext; + use std::cell::RefCell; + use std::rc::Rc; + + #[test] + fn the_window_draws_finds_the_given_claude_and_hands_its_path_back_once() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("claude.exe"); + std::fs::write(&file, "").unwrap(); + + let mut cx = TestAppContext::single(); + cx.update(|app| { + gpui_kit::init(app); + gpui_kit::component::Theme::change(gpui_kit::component::ThemeMode::Dark, None, app); + }); + let given = Some(file.clone()); + let (window, view) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| SetupView::with_reload(Mode::FirstLaunch, given, || {}, window, cx)))) + .unwrap(); + let handed_back: Rc>>> = Rc::default(); + let log = handed_back.clone(); + let _watch = cx.update(|app| { + app.subscribe(&view, move |_, ev: &SetupEvent, _| { + if let SetupEvent::Done(path) = ev { + log.borrow_mut().push(path.clone()); + } + }) + }); + for _ in 0..3 { + cx.update_window(window, |_, window, app| window.draw(app).clear(app)).unwrap(); + cx.run_until_parked(); + } + + view.read_with(&cx, |view, _| { + let found = view.checked.as_ref().expect("the check has finished"); + assert_eq!(found.claude, Some(file.clone()), "a path that exists is the claude found"); + assert!(view.can_continue()); + }); + for _ in 0..2 { + view.update(&mut cx, |view, cx| view.finish(cx)); + } + assert_eq!(*handed_back.borrow(), vec![Some(file)], "one Done, carrying the path"); + } + + #[test] + fn closing_the_window_still_hands_the_path_back() { + let mut cx = TestAppContext::single(); + cx.update(gpui_kit::init); + let (window, view) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| SetupView::with_reload(Mode::Reopened, None, || {}, window, cx)))) + .unwrap(); + let handed_back: Rc>>> = Rc::default(); + let log = handed_back.clone(); + let _watch = cx.update(|app| { + app.subscribe(&view, move |_, ev: &SetupEvent, _| { + if let SetupEvent::Done(path) = ev { + log.borrow_mut().push(path.clone()); + } + }) + }); + + // The main window holds no handle on the view, only a subscription, so neither may the test. + let weak = view.downgrade(); + drop(view); + cx.update_window(window, |_, window, app| weak.update(app, |view, cx| view.close(window, cx))).unwrap().unwrap(); + cx.run_until_parked(); + + assert_eq!(handed_back.borrow().len(), 1, "the window's Done reached its listener before the window went"); + assert!(cx.update(|app| app.windows().is_empty()), "and the window closed"); + } + + #[test] + fn closing_never_waits_on_claude_but_continuing_on_a_first_launch_does() { + let mut cx = TestAppContext::single(); + cx.update(gpui_kit::init); + let modes = [(Mode::FirstLaunch, false), (Mode::Reopened, true)]; + for (mode, expected) in modes { + // A path that does not exist leaves `claude` to discovery, so the machine decides whether it is found; + // only the Reopened answer is the same everywhere. + let (_, view) = cx + .update(|app| gpui_kit::open_window(Default::default(), app, |window, app| app.new(|cx| SetupView::with_reload(mode, None, || {}, window, cx)))) + .unwrap(); + view.update(&mut cx, |view, _| { + view.checked = Some(Checked { claude: None, gh: AuthState::Missing }); + assert_eq!(view.can_continue(), expected); + }); + } + } + + #[test] + fn the_claude_path_field_is_empty_a_real_program_or_an_error() { + let tmp = tempfile::tempdir().unwrap(); + let file = tmp.path().join("claude.exe"); + std::fs::write(&file, "").unwrap(); + + assert_eq!(parse_path(""), Ok(None)); + assert_eq!(parse_path(" "), Ok(None)); + assert_eq!(parse_path(&file.to_string_lossy()), Ok(Some(file.clone()))); + assert_eq!(parse_path(&format!("\"{}\"", file.display())), Ok(Some(file)), "pasted quotes are dropped"); + let missing = tmp.path().join("nothing-here"); + let error = parse_path(&missing.to_string_lossy()).unwrap_err(); + assert!(error.contains("is not a file or a program on PATH"), "{error}"); + } +} diff --git a/src/github/cli.rs b/src/github/cli.rs index 4483702..ccccf60 100644 --- a/src/github/cli.rs +++ b/src/github/cli.rs @@ -33,6 +33,30 @@ impl Error { } } +/// What `gh auth status` says about this machine, for the setup window. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum AuthState { + /// `gh` is not installed. + Missing, + SignedOut, + Ready, + /// `gh` ran but failed for another reason (offline, say); carries its message. + Unknown(String), +} + +impl AuthState { + fn from_status(status: Result) -> Self { + match status { + Ok(_) => AuthState::Ready, + Err(e) => match e.kind { + ErrKind::NoCli => AuthState::Missing, + ErrKind::SignedOut => AuthState::SignedOut, + ErrKind::NotGithub | ErrKind::Other => AuthState::Unknown(e.msg), + }, + } + } +} + impl std::fmt::Display for Error { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str(&self.msg) @@ -49,6 +73,14 @@ pub fn locate() -> Option { }) } +/// Find `gh` and ask it whether it is signed in. Blocking, for a background thread. +pub fn check_auth() -> AuthState { + match locate() { + Some(exe) => Gh::new(exe, crate::platform::home_dir().unwrap_or_default()).auth_status(), + None => AuthState::Missing, + } +} + /// The GitHub repository a folder belongs to. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] pub struct RepoRef { @@ -240,6 +272,11 @@ impl Gh { super::model::parse_status(&answer).ok_or_else(|| Error::other("unexpected answer from GitHub")) } + /// Whether `gh auth status` succeeds. Blocking; `cwd` does not matter for it. + pub fn auth_status(&self) -> AuthState { + AuthState::from_status(self.run(&["auth", "status"], None)) + } + /// `gh pr checkout ` in this folder. pub fn checkout(&self, number: u32) -> Result { self.run(&["pr", "checkout", &number.to_string()], None)?; @@ -453,6 +490,21 @@ mod tests { assert_eq!(classify("boom"), ErrKind::Other); } + #[test] + fn auth_status_results_become_setup_states() { + // `Gh::run` classifies a failed call's text, so the same happens here. + let failed = |text: &str| Err(Error { kind: classify(text), msg: text.into() }); + assert_eq!(AuthState::from_status(Ok("Logged in to github.com account octocat".into())), AuthState::Ready); + assert_eq!(AuthState::from_status(failed("You are not logged into any GitHub hosts. To log in, run: gh auth login")), AuthState::SignedOut); + assert_eq!(AuthState::from_status(failed("The token in keyring is invalid. To re-authenticate, run: gh auth login -h github.com")), AuthState::SignedOut); + assert_eq!( + AuthState::from_status(failed("error connecting to api.github.com")), + AuthState::Unknown("error connecting to api.github.com".into()) + ); + let not_installed = Err(Error { kind: ErrKind::NoCli, msg: "could not run gh".into() }); + assert_eq!(AuthState::from_status(not_installed), AuthState::Missing); + } + #[test] fn branch_names_are_path_encoded() { assert_eq!(encode_path("feat/a b#1"), "feat/a%20b%231"); diff --git a/src/main.rs b/src/main.rs index 6171e67..424b6d4 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,10 @@ mod terminal; mod updater; mod visual; -use gpui::{App, Bounds, KeyBinding, TitlebarOptions, WindowBounds, WindowOptions, prelude::*, px, size}; +use std::cell::RefCell; +use std::rc::Rc; + +use gpui::{AnyWindowHandle, App, Bounds, Entity, KeyBinding, TitlebarOptions, WindowBounds, WindowOptions, prelude::*, px, size}; use gpui_kit::component::TitleBar; // The Lucide icons the app draws (`IconName::` anywhere in `src`) and the title bar's window controls. The test @@ -109,6 +112,38 @@ fn install_crash_log() { })); } +type MainWindow = (AnyWindowHandle, Entity); + +/// Open the main window with its workspace; closing it asks first when sessions are still working. +fn open_main_window(initial: Vec, cx: &mut App) -> MainWindow { + let bounds = app::saved_window_bounds(cx).unwrap_or_else(|| WindowBounds::Windowed(Bounds::centered(None, size(px(1280.0), px(800.0)), cx))); + // AppKit's standard window buttons are 14 px tall; center them in the top bar so the + // traffic lights line up with its controls (and get equal space above and below). + let traffic_light_y = (panels::theme::TOPBAR_HEIGHT - 14.0) / 2.0; + // Opened through gpui_kit so the window gets the component library's Root (text inputs need it). + let (window, workspace) = gpui_kit::open_window( + WindowOptions { + window_bounds: Some(bounds), + window_min_size: Some(size(px(720.0), px(420.0))), + titlebar: Some(TitlebarOptions { + title: Some("Claudiu".into()), + traffic_light_position: Some(gpui::point(px(14.0), px(traffic_light_y))), + ..TitleBar::title_bar_options() + }), + // The top bar owns dragging and double-click (see TitleBar::window_options). + app_owns_titlebar_drag: true, + ..Default::default() + }, + cx, + |window, cx| cx.new(|cx| Workspace::new(window, initial, cx)), + ) + .expect("open window"); + let closing = workspace.clone(); + // Closing the window with live sessions asks first instead of silently killing them. + window.update(cx, |_, window, cx| window.on_window_should_close(cx, move |window, cx| closing.update(cx, |ws, cx| ws.request_quit(window, cx)))).ok(); + (window, workspace) +} + fn main() { // Hidden helper mode: the MCP server that lets Claude name its own tab (see claude/mcp.rs). if std::env::args().nth(1).as_deref() == Some(claude::mcp::FLAG) { @@ -180,40 +215,15 @@ fn main() { #[cfg(target_os = "macos")] cx.bind_keys([KeyBinding::new("cmd-q", Quit, None), KeyBinding::new("cmd-h", HideApp, None), KeyBinding::new("cmd-alt-h", HideOthers, None)]); - let bounds = app::saved_window_bounds(cx).unwrap_or_else(|| WindowBounds::Windowed(Bounds::centered(None, size(px(1280.0), px(800.0)), cx))); - // AppKit's standard window buttons are 14 px tall; center them in the top bar so the - // traffic lights line up with its controls (and get equal space above and below). - let traffic_light_y = (panels::theme::TOPBAR_HEIGHT - 14.0) / 2.0; - // Opened through gpui_kit so the window gets the component library's Root (text inputs need it). - let (window, workspace) = gpui_kit::open_window( - WindowOptions { - window_bounds: Some(bounds), - window_min_size: Some(size(px(720.0), px(420.0))), - titlebar: Some(TitlebarOptions { - title: Some("Claudiu".into()), - traffic_light_position: Some(gpui::point(px(14.0), px(traffic_light_y))), - ..TitleBar::title_bar_options() - }), - // The top bar owns dragging and double-click (see TitleBar::window_options). - app_owns_titlebar_drag: true, - ..Default::default() - }, - cx, - |window, cx| cx.new(|cx| Workspace::new(window, initial, cx)), - ) - .expect("open window"); - - let quit_target = workspace.clone(); - // Closing the window with live sessions asks first instead of silently killing them. - window - .update(cx, |_, window, cx| { - window.on_window_should_close(cx, move |window, cx| workspace.update(cx, |ws, cx| ws.request_quit(window, cx))); - }) - .ok(); - - // Cmd+Q / the Quit menu item go through the same confirmation as closing the window. + // The main window, once there is one. Cmd+Q / the Quit menu item go through the same confirmation as closing it. + let main: Rc>> = Rc::default(); + let quit_main = main.clone(); cx.on_action(move |_: &Quit, cx| { - let quit = window.update(cx, |_, window, cx| quit_target.update(cx, |ws, cx| ws.request_quit(window, cx))).unwrap_or(true); + let open = quit_main.borrow().clone(); + let quit = match open { + Some((window, workspace)) => window.update(cx, |_, window, cx| workspace.update(cx, |ws, cx| ws.request_quit(window, cx))).unwrap_or(true), + None => true, + }; if quit { cx.quit(); } @@ -230,6 +240,25 @@ fn main() { } }) .detach(); + + // A first launch (no state file) starts with the setup window alone. Asked before anything loads the store. + if store::Store::is_first_launch(&store::Store::default_path()) { + let (setup_window, setup) = gpui_kit::open_window(app::setup_window_options(cx), cx, |window, cx| { + cx.new(|cx| app::SetupView::new(app::SetupMode::FirstLaunch, None, window, cx)) + }) + .expect("open setup window"); + cx.subscribe(&setup, move |_, ev: &app::SetupEvent, cx| { + let app::SetupEvent::Done(claude_path) = ev else { return }; + // The main window opens before the setup window closes: closing the last window quits the app. + let (window, workspace) = open_main_window(initial.clone(), cx); + workspace.update(cx, |ws, cx| ws.apply_setup(claude_path.clone(), cx)); + *main.borrow_mut() = Some((window, workspace)); + setup_window.update(cx, |_, window, _| window.remove_window()).ok(); + }) + .detach(); + } else { + *main.borrow_mut() = Some(open_main_window(initial, cx)); + } cx.activate(true); }); } diff --git a/src/panels/workspace_view.rs b/src/panels/workspace_view.rs index 3d33004..2251556 100644 --- a/src/panels/workspace_view.rs +++ b/src/panels/workspace_view.rs @@ -69,7 +69,16 @@ impl Workspace { .child(title), ) .when_some(cwd, |d, p| { - d.child(div().flex_none().text_size(crate::panels::scale::px(11.5)).text_color(hsla(theme::TEXT_FAINT)).child(short_path(&p))) + d.child( + div() + .min_w_0() + .overflow_hidden() + .whitespace_nowrap() + .text_ellipsis() + .text_size(crate::panels::scale::px(11.5)) + .text_color(hsla(theme::TEXT_FAINT)) + .child(short_path(&p)), + ) }) .when_some(branch.zip(repo), |d, (b, repo)| { // Click: switch branch or create one (see Workspace::open_branch_menu). @@ -765,6 +774,7 @@ fn settings_body(page: SettingsPage, modal: &Modal, scroll: &crate::panels::glid .gap(px(10.0)) .child(field("SHELL", shell)) .child(field("CLAUDE CODE PATH", claude)) + .child(div().flex().child(button("settings-check-setup", "Check setup", false).on_click(cx.listener(|ws, _: &ClickEvent, window, cx| ws.act(Act::OpenSetup, window, cx))))) .child( div() .h(px(32.0)) diff --git a/src/platform.rs b/src/platform.rs index 797c4d7..6b5a4d8 100644 --- a/src/platform.rs +++ b/src/platform.rs @@ -51,7 +51,139 @@ pub fn home_dir() -> Option { /// PATH lookup (honors PATHEXT on Windows). pub fn find_executable(name: &str) -> Option { - which::which(name).ok() + let found = which::which(name).ok(); + #[cfg(target_os = "macos")] + let found = found.or_else(|| { + let path = LOGIN_PATH.lock().ok()?.clone()?; + which::which_in(name, Some(path), std::env::current_dir().ok()?).ok() + }); + found +} + +/// The PATH of the user's login shell, as `reload_path` last read it. A Finder-launched app gets a minimal PATH, and +/// the environment of a running process is not changed here (`set_var` is unsafe beside other threads on Unix), so +/// `find_executable` looks here as well. Sessions already start through the login shell (`through_login_shell`). +#[cfg(target_os = "macos")] +static LOGIN_PATH: std::sync::Mutex> = std::sync::Mutex::new(None); + +/// Look for the PATH again, for a tool installed since Claudiu started or one that only the shell's startup files +/// put on the PATH. Windows reads the system and user PATH from the registry and uses it for this process and the +/// programs it starts. macOS asks the login shell (blocking, up to a few seconds). Call it off the UI thread. +pub fn reload_path() { + #[cfg(target_os = "windows")] + { + use windows_sys::Win32::System::Registry::{HKEY_CURRENT_USER, HKEY_LOCAL_MACHINE}; + let system = registry_path(HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment"); + let user = registry_path(HKEY_CURRENT_USER, "Environment"); + // Without either value the PATH stays as it is. + if system.is_none() && user.is_none() { + return; + } + let registry: Vec = [system, user].into_iter().flatten().flat_map(|text| std::env::split_paths(&text).collect::>()).collect(); + let current = std::env::var_os("PATH").unwrap_or_default(); + // SAFETY: on Windows `set_var` is safe to call from any thread (std's documentation says so). + unsafe { std::env::set_var("PATH", rebuilt_path(®istry, ¤t)) }; + } + #[cfg(target_os = "macos")] + { + if let Some(text) = login_shell_path() { + let shell_dirs: Vec = std::env::split_paths(&text).collect(); + let current = std::env::var_os("PATH").unwrap_or_default(); + if let Ok(mut slot) = LOGIN_PATH.lock() { + *slot = Some(rebuilt_path(&shell_dirs, ¤t)); + } + } + } +} + +/// Ask the user's login shell for its PATH. Interactive (`-i`) so `.zshrc` runs too, which is where nvm and friends +/// add theirs. +#[cfg(target_os = "macos")] +fn login_shell_path() -> Option { + let shell = std::env::var_os("SHELL").filter(|s| !s.is_empty()).unwrap_or_else(|| "/bin/zsh".into()); + path_from_shell(&shell, &print_path_script(), std::time::Duration::from_secs(5)) +} + +#[cfg(any(target_os = "macos", test))] +const PATH_BEGIN: &str = "< String { + format!("printf '%s%s%s' '{PATH_BEGIN}' \"$PATH\" '{PATH_END}'") +} + +/// Run `script` in `shell` as a login shell and return the PATH it printed. Startup files may print anything, so the +/// PATH sits between markers. A shell that has not answered after `wait` is killed and gives `None`, as does any shell +/// that fails to run it. +#[cfg(any(target_os = "macos", test))] +fn path_from_shell(shell: &OsStr, script: &str, wait: std::time::Duration) -> Option { + use std::io::Read; + let mut child = Command::new(shell) + .args(["-l", "-i", "-c", script]) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .spawn() + .ok()?; + let mut stdout = child.stdout.take()?; + let (sender, receiver) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let mut text = String::new(); + let _ = stdout.read_to_string(&mut text); + let _ = sender.send(text); + }); + let output = receiver.recv_timeout(wait); + // Killing a shell that already ended is harmless, and it must not be left running if it did not. + let _ = child.kill(); + let _ = child.wait(); + path_between_markers(&output.ok()?).map(std::ffi::OsString::from) +} + +/// The text between the markers, ignoring whatever the shell's startup files printed around them. +#[cfg(any(target_os = "macos", test))] +fn path_between_markers(output: &str) -> Option<&str> { + let after = output.split_once(PATH_BEGIN)?.1; + Some(after.split_once(PATH_END)?.0) +} + +/// The registry's directories first, then whatever this process had that the registry lacks (for example folders a +/// launcher added for Claudiu alone). Each directory appears once. +fn rebuilt_path(registry: &[PathBuf], current: &OsStr) -> std::ffi::OsString { + let mut dirs: Vec = Vec::new(); + for dir in registry.iter().cloned().chain(std::env::split_paths(current)) { + if !dir.as_os_str().is_empty() && !dirs.iter().any(|seen| path_key(seen) == path_key(&dir)) { + dirs.push(dir); + } + } + std::env::join_paths(dirs).unwrap_or_else(|_| current.to_owned()) +} + +/// The `Path` value under a registry key, with `%VARIABLES%` already expanded. +#[cfg(target_os = "windows")] +fn registry_path(root: windows_sys::Win32::System::Registry::HKEY, subkey: &str) -> Option { + use windows_sys::Win32::System::Registry::{RRF_RT_REG_EXPAND_SZ, RRF_RT_REG_SZ, RegGetValueW}; + let subkey: Vec = subkey.encode_utf16().chain(Some(0)).collect(); + let name: Vec = "Path".encode_utf16().chain(Some(0)).collect(); + let kinds = RRF_RT_REG_SZ | RRF_RT_REG_EXPAND_SZ; + let mut bytes = 0u32; + // SAFETY: both calls get NUL-terminated names and a buffer of the size they report. + unsafe { + if RegGetValueW(root, subkey.as_ptr(), name.as_ptr(), kinds, std::ptr::null_mut(), std::ptr::null_mut(), &mut bytes) != 0 { + return None; + } + let mut text = vec![0u16; (bytes as usize).div_ceil(2)]; + bytes = (text.len() * 2) as u32; + if RegGetValueW(root, subkey.as_ptr(), name.as_ptr(), kinds, std::ptr::null_mut(), text.as_mut_ptr().cast(), &mut bytes) != 0 { + return None; + } + // The reported size includes the closing NUL. + text.truncate((bytes as usize / 2).saturating_sub(1)); + Some(String::from_utf16_lossy(&text)) + } } /// A program typed by the user: an existing file, or a name found on PATH. @@ -278,6 +410,64 @@ fn expand_env(s: &str) -> String { mod tests { use super::*; + #[test] + fn a_rebuilt_path_lists_the_registry_first_and_keeps_the_rest_once() { + let dir = |name: &str| PathBuf::from(name); + let current = std::env::join_paths(["extra", "shared", "extra"]).unwrap(); + let rebuilt = rebuilt_path(&[dir("fresh"), dir("shared"), dir("")], ¤t); + let dirs: Vec = std::env::split_paths(&rebuilt).collect(); + assert_eq!(dirs, vec![dir("fresh"), dir("shared"), dir("extra")]); + if cfg!(windows) { + let rebuilt = rebuilt_path(&[dir("C:/Tools/Bin")], std::ffi::OsStr::new("c:\\tools\\bin\\")); + assert_eq!(std::env::split_paths(&rebuilt).count(), 1, "the same folder in another case is one entry"); + } + } + + #[test] + fn a_shells_path_is_found_between_the_markers_whatever_else_it_printed() { + let output = format!("Last login: today +Welcome! +{PATH_BEGIN}/usr/bin:/opt/tools{PATH_END} +bye +"); + assert_eq!(path_between_markers(&output), Some("/usr/bin:/opt/tools")); + assert_eq!(path_between_markers(&format!("{PATH_BEGIN}{PATH_END}")), Some("")); + assert_eq!(path_between_markers("the shell printed no markers"), None); + assert_eq!(path_between_markers(&format!("{PATH_BEGIN}/usr/bin")), None, "a cut-off answer is not used"); + } + + /// A shell that takes `-l -i -c`: `/bin/sh` on macOS, Git's bash on Windows (not the WSL launcher in System32, + /// which fails without a distribution). `None` when the machine has neither. + fn posix_shell() -> Option { + let candidates = if cfg!(windows) { vec![PathBuf::from(expand_env(r"%ProgramFiles%\Git\bin\bash.exe"))] } else { vec![PathBuf::from("/bin/sh")] }; + candidates.into_iter().find(|p| p.is_file()) + } + + #[test] + fn a_shell_answers_with_its_path_and_a_hung_one_is_given_up_on() { + let Some(bash) = posix_shell() else { return }; + let asked = std::time::Instant::now(); + let path = path_from_shell(bash.as_os_str(), &print_path_script(), std::time::Duration::from_secs(20)).expect("bash printed its PATH"); + assert!(!path.is_empty()); + assert!(asked.elapsed() < std::time::Duration::from_secs(20), "it answered, not timed out"); + + let hung = format!("sleep 30; {}", print_path_script()); + let asked = std::time::Instant::now(); + assert_eq!(path_from_shell(bash.as_os_str(), &hung, std::time::Duration::from_millis(500)), None); + assert!(asked.elapsed() < std::time::Duration::from_secs(10), "the wait ended at the timeout, not when the shell did"); + + assert_eq!(path_from_shell(OsStr::new("no-such-shell-xyz"), &print_path_script(), std::time::Duration::from_secs(1)), None); + } + + #[test] + #[cfg(windows)] + fn the_registry_path_of_this_machine_can_be_read() { + use windows_sys::Win32::System::Registry::HKEY_LOCAL_MACHINE; + let system = registry_path(HKEY_LOCAL_MACHINE, r"SYSTEM\CurrentControlSet\Control\Session Manager\Environment").expect("the system Path value exists"); + assert!(!system.contains('%'), "variables are expanded: {system}"); + assert!(system.to_lowercase().contains("system32"), "{system}"); + } + #[test] fn typed_programs_resolve_only_when_they_exist() { let exe = std::env::current_exe().unwrap(); diff --git a/src/store.rs b/src/store.rs index 524056b..76c2ab8 100644 --- a/src/store.rs +++ b/src/store.rs @@ -409,6 +409,12 @@ impl Store { dir.join("state.json") } + /// No state file yet: Claudiu has never run here. Ask before anything calls `load`, which moves a corrupt file aside + /// (a corrupt file still means the user has been here). + pub fn is_first_launch(path: &Path) -> bool { + !path.exists() + } + /// Load tolerant of missing/corrupt files: a corrupt file is moved aside, never overwritten silently. pub fn load(path: PathBuf) -> Self { let mut data = Data { version: 1, layout: Layout { sidebar_visible: true, ..Default::default() }, ..Default::default() }; @@ -915,6 +921,18 @@ mod tests { assert!(path.with_extension("json.corrupt").exists(), "corrupt state is preserved, not destroyed"); } + #[test] + fn a_launch_is_the_first_only_while_there_is_no_state_file() { + let tmp = tempfile::tempdir().unwrap(); + let path = tmp.path().join("state.json"); + assert!(Store::is_first_launch(&path), "nothing saved yet"); + Store::load(path.clone()).save(); + assert!(!Store::is_first_launch(&path), "a saved state file ends the first launch"); + + fs::write(&path, "{ not json").unwrap(); + assert!(!Store::is_first_launch(&path), "a corrupt state file still means Claudiu ran here"); + } + #[test] fn window_geometry_survives_a_save_and_old_state_files_load_without_it() { let tmp = tempfile::tempdir().unwrap();