diff --git a/CHANGELOG.md b/CHANGELOG.md index 3298e9c..a9855f0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -9,6 +9,13 @@ This changelog is automatically generated by AI when releases are published. ## [Unreleased] +## [3.11.0] - 2026-11-15 + +### Changed + +- **`autter dash` opens the page for where you are.** It used to open `app.autter.dev/me`, which is not a page in the app, so everyone landed on the generic dashboard, even inside a repository. It now opens the current repository's page when the repository's default remote (`owner/name`) is connected to your organization (`--org`, else your active one), else the organization dashboard, else (signed out) the app's dashboard. One line on stderr says why when it falls back ("acme/api is not connected to acme; opening the organization dashboard."). New flags: `--repo `, `--org `, `--no-open` (print the URL instead of opening it) and `--json` (`url`, `target`, `organization`, `repository`, `repository_full_name`, `opened`, `fallback_reason`). The repository lookup waits at most 5 seconds and reads the organization's repository list without starting an index refresh (`ask/status?warm=0`); an API without that flag still answers. See [docs/system-investigations.md](docs/system-investigations.md). +- **`autter ask` scopes a new question to the repository you are in.** Without `--repo`, a question asked inside a git repository that is connected to the organization is scoped to it, so the assistant no longer asks which repository you mean. Answers that point at Autter pages end with an "Open in Autter" list of absolute links (from APIs that return them). + ## [3.10.1] - 2026-11-15 ### Fixed diff --git a/Cargo.lock b/Cargo.lock index a48be24..db6c052 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -258,7 +258,7 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "autter" -version = "3.10.1" +version = "3.11.0" dependencies = [ "autter", "base64", diff --git a/Cargo.toml b/Cargo.toml index 42a3154..ad9679e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -5,7 +5,7 @@ resolver = "3" [package] name = "autter" -version = "3.10.1" +version = "3.11.0" edition = "2024" default-run = "autter" diff --git a/docs/system-investigations.md b/docs/system-investigations.md index 2123e1e..de65ad9 100644 --- a/docs/system-investigations.md +++ b/docs/system-investigations.md @@ -17,6 +17,10 @@ Questions use captured Runtime evidence and source code to explain root causes, Use `--org ` for another organization you belong to and `--json` for complete structured output. `--mode codebase` and `--mode reviews` select the existing assistants. Resuming with `--thread` restores that thread's mode and repository unless you explicitly specify them; changing its scope requires a new thread. +Without `--repo`, a new question run inside a git repository is scoped to that repository when its default remote (`owner/name`) is connected to the organization; otherwise it goes out unscoped. Answers that point at Autter pages (a pull request, a file at a line, a scan finding, a Runtime issue) end with an **Open in Autter** list of absolute links, and links inside the answer are absolute too. + +`autter dash` opens the page for where you are: the current repository's page when it is connected to the organization (`--org`, else your active one), else the organization dashboard, else (signed out) the app's dashboard. `--repo ` picks the repository, `--no-open` prints the URL instead of opening it, and `--json` prints `{ url, target, organization, repository, repository_full_name, opened, fallback_reason }`, where `target` is `repo`, `org` or `home` and `fallback_reason` is null or one of `not_in_git_repo`, `no_remote`, `not_signed_in`, `repo_not_connected`, `lookup_failed`. The lookup waits at most 5 seconds and reads the repository list without starting an index refresh. + ## From a Runtime issue to the code behind it `autter lineage ` prints the chain behind one Runtime issue (its id starts with `ri_`), top to bottom: diff --git a/src/commands/arg_parser.rs b/src/commands/arg_parser.rs index 241aff9..06b7894 100644 --- a/src/commands/arg_parser.rs +++ b/src/commands/arg_parser.rs @@ -666,12 +666,24 @@ autter sync open HelpEntry { name: "dashboard", aliases: &["dash", "personal-dashboard", "personal_dashboard"], - summary: "Open your personal dashboard in the browser", + summary: "Open the Autter page for this repository in the browser", body: "\ -autter dashboard - - Open your personal dashboard in the browser - (https://app.autter.dev/me, or your configured web app URL).", +autter dash [--org ] [--repo ] [--no-open] [--json] + + Open the Autter page for where you are (https://app.autter.dev, or your + configured web app URL): + - inside a git repository connected to your organization: its page + - otherwise: the organization dashboard + - when signed out: the app's dashboard + + --org Look in this organization instead of the active one + --repo Open this repository (owner/name or name) instead of the + current one + --no-open Print the URL instead of opening a browser + --json Print {url, target, organization, repository, + repository_full_name, opened, fallback_reason}; target is + repo, org or home, fallback_reason one of not_in_git_repo, + no_remote, not_signed_in, repo_not_connected, lookup_failed", }, HelpEntry { name: "bg", @@ -880,7 +892,7 @@ autter login [--token ] name: "ask", aliases: &[], summary: "Investigate your system with Runtime evidence", - body: "autter ask [--repo ] [--org ] [--thread ] [--mode system|codebase|reviews] [--json]\n\n Get root causes, impact, and recommended fixes. Ask it \"why did this happen\"\n and \"what is the impact\" questions: it answers them from Runtime evidence.\n Questions and answers are saved in the same private thread history as Dashboard Ask. Use --thread to resume.\n Sign in with autter login. Default mode: system.", + body: "autter ask [--repo ] [--org ] [--thread ] [--mode system|codebase|reviews] [--json]\n\n Get root causes, impact, and recommended fixes. Ask it \"why did this happen\"\n and \"what is the impact\" questions: it answers them from Runtime evidence.\n Questions and answers are saved in the same private thread history as Dashboard Ask. Use --thread to resume.\n Without --repo, a new question asked inside a connected repository is scoped to it.\n Sign in with autter login. Default mode: system.", }, HelpEntry { name: "logs", diff --git a/src/commands/ask.rs b/src/commands/ask.rs index 065243a..28baf13 100644 --- a/src/commands/ask.rs +++ b/src/commands/ask.rs @@ -249,6 +249,26 @@ pub(crate) fn org_api_context( Ok((context, slug.to_owned())) } +/// The current git repository's `owner/name` when it is connected to the +/// organization, so a new question is scoped to the repo you are in. `None` +/// outside a repo, without a remote, for an unconnected repo, or when the +/// lookup fails (the question then goes out unscoped, as before). +fn current_connected_repository(context: &ApiContext, slug: &str) -> Option { + use crate::commands::personal_dashboard::{ + current_repository_candidate, fetch_connected_repositories, match_repository, + }; + let wanted = current_repository_candidate().ok()?; + let repos = fetch_connected_repositories(&context.clone().with_timeout(5), slug)?; + match_repository(&wanted, &repos).map(|repo| repo.full_name) +} + +/// Strip terminal control sequences, keeping newlines and tabs. +fn printable(text: &str) -> String { + text.chars() + .filter(|c| !c.is_control() || *c == '\n' || *c == '\t') + .collect() +} + pub(crate) fn component(value: &str) -> String { url::form_urlencoded::byte_serialize(value.as_bytes()).collect() } @@ -267,6 +287,8 @@ fn run(command: &str, mut options: Options) -> Result<(), AutterError> { if options.mode.is_none() { options.mode = thread["mode"].as_str().map(str::to_owned); } + } else if options.repository.is_none() { + options.repository = current_connected_repository(&context, &slug); } response_json(context.post_json(&format!("{base}/chat"), &json!({ "question": options.words.join(" "), "repository": options.repository, "mode": options.mode.unwrap_or_else(|| "system".into()), "threadId": options.thread, "format": "json" }))?)? } @@ -310,15 +332,32 @@ fn run(command: &str, mut options: Options) -> Result<(), AutterError> { match command { "ask" => { // Preserve newlines in prose while stripping terminal control sequences. - println!( - "{}", - result["answer"] - .as_str() - .unwrap_or("") - .chars() - .filter(|c| !c.is_control() || *c == '\n' || *c == '\t') - .collect::() - ); + println!("{}", printable(result["answer"].as_str().unwrap_or(""))); + // Pages the answer points at, as absolute URLs (newer APIs only). + let links: Vec<(String, String)> = result["links"] + .as_array() + .map(|links| { + links + .iter() + .filter_map(|link| { + let url = link["url"].as_str()?; + url.starts_with("https://").then(|| { + ( + printable(link["label"].as_str().unwrap_or(url)) + .replace('\n', " "), + printable(url), + ) + }) + }) + .collect() + }) + .unwrap_or_default(); + if !links.is_empty() { + println!("\nOpen in Autter:"); + for (label, url) in links { + println!(" {label}: {url}"); + } + } if !arg_parser::quiet() { println!("\nThread: {}", result["threadId"].as_str().unwrap_or("")); } diff --git a/src/commands/onboard.rs b/src/commands/onboard.rs index 750b6ca..ecad2ce 100644 --- a/src/commands/onboard.rs +++ b/src/commands/onboard.rs @@ -702,7 +702,7 @@ fn render_finished(connected: bool, report: &SetupReport, caps: &TermCaps) -> St )); out.push_str(&command("autter log", "git log with AI authorship stats")); if connected { - out.push_str(&command("autter dash", "open your personal dashboard")); + out.push_str(&command("autter dash", "open this repository in Autter")); } out.push('\n'); out.push_str(&format!( diff --git a/src/commands/personal_dashboard.rs b/src/commands/personal_dashboard.rs index 0ea16e1..3a873c6 100644 --- a/src/commands/personal_dashboard.rs +++ b/src/commands/personal_dashboard.rs @@ -1,28 +1,380 @@ -/// Handle the `autter personal-dashboard` command -pub fn handle_personal_dashboard(args: &[String]) { - crate::commands::arg_parser::reject_any_args("dashboard", args); - let dashboard_url = personal_dashboard_url(); +//! `autter dash`: open the Autter page for where you are. +//! +//! Inside a git repository that is connected to your organization this opens +//! that repository's page; otherwise the organization dashboard; when you are +//! not signed in, the app's dashboard. The repository is matched by its +//! default remote (`owner/name`) against the organization's connected +//! repositories, read with a read-only status request that does not start an +//! index refresh. + +use crate::api::client::ApiContext; +use crate::commands::arg_parser::{self, ScanMode}; +use crate::commands::ask::{component, org_api_context}; +use crate::commands::output::{ErrorKind, fail}; +use serde::Serialize; +use serde_json::Value; + +/// How long `dash` waits for the repository lookup before falling back to the +/// organization dashboard. +const LOOKUP_TIMEOUT_SECS: u64 = 5; + +#[derive(Debug, Default, PartialEq, Eq)] +struct DashOptions { + organization: Option, + repository: Option, + no_open: bool, +} + +fn parse_options(args: &[String]) -> Result { + let mut options = DashOptions::default(); + let mut index = 0; + while index < args.len() { + let flag = args[index].as_str(); + match flag { + "--no-open" => { + options.no_open = true; + index += 1; + } + "--org" | "--repo" => { + let value = args + .get(index + 1) + .filter(|value| !value.starts_with('-') && !value.trim().is_empty()) + .ok_or_else(|| format!("{flag} requires a value"))?; + if flag == "--org" { + options.organization = Some(value.clone()); + } else { + options.repository = Some(value.clone()); + } + index += 2; + } + _ => return Err(format!("unknown option for dashboard: {flag}")), + } + } + Ok(options) +} + +/// Which page `dash` opens. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum DashTarget { + /// The repository's page in the organization. + Repo, + /// The organization dashboard. + Org, + /// The app's dashboard (organization picker). + Home, +} + +/// Why `dash` did not open the repository page. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)] +#[serde(rename_all = "snake_case")] +pub(crate) enum FallbackReason { + NotInGitRepo, + NoRemote, + NotSignedIn, + RepoNotConnected, + LookupFailed, +} + +/// A connected repository: its short `name` (the URL segment) and `owner/name`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) struct ConnectedRepo { + pub name: String, + pub full_name: String, +} - eprintln!("Opening dashboard: {}", dashboard_url); +/// Result of looking the candidate up in the organization. +#[derive(Debug, Clone, PartialEq, Eq)] +pub(crate) enum RepoLookup { + Found(ConnectedRepo), + NotConnected, + Failed, +} + +#[derive(Debug, Clone, PartialEq, Eq, Serialize)] +pub(crate) struct DashResolution { + pub url: String, + pub target: DashTarget, + pub organization: Option, + pub repository: Option, + pub repository_full_name: Option, + pub fallback_reason: Option, + /// The `owner/name` (or name) that was looked up, for the fallback message. + #[serde(skip)] + pub candidate: Option, +} - if open_browser(&dashboard_url).is_err() { - eprintln!("Could not open browser automatically."); - eprintln!("Visit this URL in your browser:"); - eprintln!(" {}", dashboard_url); +/// `web/`, with every segment percent-encoded and no double slash. +fn web_url(web_app_base: &str, segments: &[&str]) -> String { + let base = web_app_base.trim_end_matches('/'); + if let Ok(mut url) = url::Url::parse(base) { + let pushed = match url.path_segments_mut() { + Ok(mut path) => { + path.pop_if_empty(); + for segment in segments { + path.push(segment); + } + true + } + Err(()) => false, + }; + if pushed { + return url.to_string(); + } + } + // Not a URL we can parse (should not happen): join encoded segments. + let mut out = base.to_string(); + for segment in segments { + out.push('/'); + out.push_str(&component(segment)); } + out } -/// Resolve the user-facing personal dashboard URL. +/// Pick the page to open. Pure: every input that needs I/O is resolved first. /// -/// This must use the web-app base ([`crate::commands::login::web_app_url`]), -/// not the API base: `api.autter.dev/me` 404s while `app.autter.dev/me` is -/// the working page. -pub(crate) fn personal_dashboard_url() -> String { - build_personal_dashboard_url(&crate::commands::login::web_app_url()) +/// * `organization`: the org slug, or `None` when not signed in. +/// * `candidate`: the repository to look for (`--repo`, else the current +/// repo's `owner/name`), or why there is none. +/// * `lookup`: matches the candidate in the organization; only called when +/// there are both an organization and a candidate. +pub(crate) fn resolve_dash_target( + web_app_base: &str, + organization: Option<&str>, + candidate: Result<&str, FallbackReason>, + lookup: impl FnOnce(&str, &str) -> RepoLookup, +) -> DashResolution { + let candidate_name = candidate.ok().map(str::to_owned); + let Some(org) = organization else { + return DashResolution { + url: web_url(web_app_base, &["dashboard"]), + target: DashTarget::Home, + organization: None, + repository: None, + repository_full_name: None, + fallback_reason: Some(FallbackReason::NotSignedIn), + candidate: candidate_name, + }; + }; + let org_page = |reason: FallbackReason| DashResolution { + url: web_url(web_app_base, &[org]), + target: DashTarget::Org, + organization: Some(org.to_owned()), + repository: None, + repository_full_name: None, + fallback_reason: Some(reason), + candidate: candidate_name.clone(), + }; + let wanted = match candidate { + Ok(wanted) => wanted, + Err(reason) => return org_page(reason), + }; + match lookup(org, wanted) { + RepoLookup::Found(repo) => DashResolution { + url: web_url(web_app_base, &[org, "repositories", &repo.name]), + target: DashTarget::Repo, + organization: Some(org.to_owned()), + repository: Some(repo.name), + repository_full_name: Some(repo.full_name), + fallback_reason: None, + candidate: candidate_name.clone(), + }, + RepoLookup::NotConnected => org_page(FallbackReason::RepoNotConnected), + RepoLookup::Failed => org_page(FallbackReason::LookupFailed), + } +} + +/// `owner/name` from a normalized `https://host/owner/name` remote URL. +pub(crate) fn owner_and_name(normalized_remote: &str) -> Option { + let url = url::Url::parse(normalized_remote).ok()?; + let path = url.path().trim_matches('/'); + let path = path.strip_suffix(".git").unwrap_or(path); + path.contains('/').then(|| path.to_owned()) +} + +/// Find `wanted` among the connected repositories: `owner/name` matches the +/// full name, a bare name matches the short name; both ignore case. +pub(crate) fn match_repository(wanted: &str, repos: &[ConnectedRepo]) -> Option { + let wanted = wanted.trim().trim_matches('/'); + let found = if wanted.contains('/') { + repos + .iter() + .find(|repo| repo.full_name.eq_ignore_ascii_case(wanted)) + } else { + repos + .iter() + .find(|repo| repo.name.eq_ignore_ascii_case(wanted)) + }; + found.cloned() +} + +/// Parse the `repositories` list of an `ask/status` response. +pub(crate) fn connected_repositories(status: &Value) -> Option> { + let list = status.get("repositories")?.as_array()?; + Some( + list.iter() + .filter_map(|repo| { + Some(ConnectedRepo { + name: repo.get("name")?.as_str()?.to_owned(), + full_name: repo.get("fullName")?.as_str()?.to_owned(), + }) + }) + .collect(), + ) +} + +/// The organization's connected repositories, read without side effects +/// (`warm=0`: no index refresh). `None` on any failure. +pub(crate) fn fetch_connected_repositories( + context: &ApiContext, + slug: &str, +) -> Option> { + let response = context + .get(&format!( + "/api/cli/orgs/{}/ask/status?warm=0", + component(slug) + )) + .ok()?; + if response.status_code != 200 { + return None; + } + let value: Value = serde_json::from_str(response.as_str().ok()?).ok()?; + connected_repositories(&value) +} + +/// The current repository's `owner/name`, or why there is none. +pub(crate) fn current_repository_candidate() -> Result { + let repo = crate::git::repository::find_repository(&Vec::::new()) + .map_err(|_| FallbackReason::NotInGitRepo)?; + crate::authorship::post_commit::current_repo_url(&repo) + .as_deref() + .and_then(owner_and_name) + .ok_or(FallbackReason::NoRemote) +} + +fn fallback_message(resolution: &DashResolution) -> Option { + let org = resolution + .organization + .as_deref() + .unwrap_or("your organization"); + let candidate = resolution.candidate.as_deref().unwrap_or("This repository"); + Some(match resolution.fallback_reason? { + FallbackReason::NotSignedIn => "Not signed in; opening the Autter dashboard. Run `autter login` to open your repository's page.".to_string(), + FallbackReason::NotInGitRepo => { + "Not in a git repository; opening the organization dashboard.".to_string() + } + FallbackReason::NoRemote => { + "This repository has no remote; opening the organization dashboard.".to_string() + } + FallbackReason::RepoNotConnected => { + format!("{candidate} is not connected to {org}; opening the organization dashboard.") + } + FallbackReason::LookupFailed => { + format!("Could not look up {candidate} in {org}; opening the organization dashboard.") + } + }) } -fn build_personal_dashboard_url(web_app_base: &str) -> String { - format!("{}/me", web_app_base.trim_end_matches('/')) +#[derive(Serialize)] +struct DashReport<'a> { + #[serde(flatten)] + resolution: &'a DashResolution, + opened: bool, +} + +/// Handle `autter dash` (also `dashboard`, `personal-dashboard`). +pub fn handle_personal_dashboard(args: &[String]) { + let parsed = arg_parser::pre_parse(args, ScanMode::Full, true) + .unwrap_or_else(|error| fail(ErrorKind::Usage, format!("error: {error}"))); + arg_parser::merge_global_flags(&parsed.flags); + if parsed.flags.help { + arg_parser::print_command_help("dashboard"); + return; + } + if let Some(directory) = parsed.flags.change_dir + && let Err(error) = std::env::set_current_dir(directory) + { + fail(ErrorKind::Usage, format!("error: {error}")); + } + let options = parse_options(&parsed.rest) + .unwrap_or_else(|error| fail(ErrorKind::Usage, format!("error: {error}"))); + + let web = crate::commands::login::web_app_url(); + let signed_in = ApiContext::new(None).auth_token.is_some(); + // An explicit --org that the token cannot use is an error; without --org, + // a token with no usable organization just means "not signed in". + let org_context = if signed_in { + match org_api_context(options.organization.as_deref(), LOOKUP_TIMEOUT_SECS) { + Ok(found) => Some(found), + Err(error) if options.organization.is_some() => { + fail(ErrorKind::Usage, format!("error: {error}")) + } + Err(_) => None, + } + } else if options.organization.is_some() { + fail( + ErrorKind::NotSignedIn, + "error: Sign in with `autter login` to open an organization.", + ) + } else { + None + }; + + let candidate = match options.repository.clone() { + Some(repo) => Ok(repo), + None => current_repository_candidate(), + }; + let resolution = resolve_dash_target( + &web, + org_context.as_ref().map(|(_, slug)| slug.as_str()), + candidate.as_deref().map_err(|reason| *reason), + |slug, wanted| { + let Some((context, _)) = org_context.as_ref() else { + return RepoLookup::Failed; + }; + match fetch_connected_repositories(context, slug) { + Some(repos) => match match_repository(wanted, &repos) { + Some(repo) => RepoLookup::Found(repo), + None => RepoLookup::NotConnected, + }, + None => RepoLookup::Failed, + } + }, + ); + + let json = arg_parser::json(); + let mut opened = false; + if options.no_open { + if !json { + println!("{}", resolution.url); + } + } else { + if !json { + eprintln!("Opening dashboard: {}", resolution.url); + } + opened = open_browser(&resolution.url).is_ok(); + if !opened { + eprintln!("Could not open browser automatically."); + eprintln!("Visit this URL in your browser:"); + eprintln!(" {}", resolution.url); + } + } + if let Some(note) = fallback_message(&resolution) + && !arg_parser::quiet() + && !json + { + eprintln!("{note}"); + } + if json { + let report = DashReport { + resolution: &resolution, + opened, + }; + match serde_json::to_string(&report) { + Ok(out) => println!("{out}"), + Err(error) => fail(ErrorKind::Runtime, format!("error: {error}")), + } + } } /// Attempt to open a URL in the system's default browser @@ -58,46 +410,180 @@ pub(crate) fn open_browser(url: &str) -> Result<(), String> { mod tests { use super::*; + const WEB: &str = "https://app.autter.dev"; + + fn args(values: &[&str]) -> Vec { + values.iter().map(|value| value.to_string()).collect() + } + + fn repos() -> Vec { + vec![ + ConnectedRepo { + name: "api".into(), + full_name: "Acme/api".into(), + }, + ConnectedRepo { + name: "web".into(), + full_name: "acme/web".into(), + }, + ] + } + #[test] - fn builds_personal_dashboard_url_from_web_app_base() { + fn dash_parses_flags() { + assert_eq!(parse_options(&[]).unwrap(), DashOptions::default()); assert_eq!( - build_personal_dashboard_url("https://app.autter.dev"), - "https://app.autter.dev/me" + parse_options(&args(&["--org", "acme", "--repo", "acme/api", "--no-open"])).unwrap(), + DashOptions { + organization: Some("acme".into()), + repository: Some("acme/api".into()), + no_open: true, + } ); - // Trailing slashes must not produce a double slash. + assert!(parse_options(&args(&["--org"])).is_err()); + assert!(parse_options(&args(&["--repo", "--no-open"])).is_err()); + assert!(parse_options(&args(&["--bogus"])).is_err()); + assert!(parse_options(&args(&["extra"])).is_err()); + } + + #[test] + fn dash_opens_the_repository_page_when_connected() { + let out = resolve_dash_target(WEB, Some("acme"), Ok("acme/api"), |org, wanted| { + assert_eq!((org, wanted), ("acme", "acme/api")); + RepoLookup::Found(ConnectedRepo { + name: "api".into(), + full_name: "acme/api".into(), + }) + }); + assert_eq!(out.url, "https://app.autter.dev/acme/repositories/api"); + assert_eq!(out.target, DashTarget::Repo); + assert_eq!(out.repository.as_deref(), Some("api")); + assert_eq!(out.repository_full_name.as_deref(), Some("acme/api")); + assert_eq!(out.fallback_reason, None); + } + + #[test] + fn dash_falls_back_to_the_org_with_a_reason() { + for reason in [FallbackReason::NotInGitRepo, FallbackReason::NoRemote] { + let out = resolve_dash_target(WEB, Some("acme"), Err(reason), |_, _| { + panic!("no lookup without a candidate") + }); + assert_eq!(out.url, "https://app.autter.dev/acme"); + assert_eq!(out.target, DashTarget::Org); + assert_eq!(out.fallback_reason, Some(reason)); + } + for (lookup, reason) in [ + (RepoLookup::NotConnected, FallbackReason::RepoNotConnected), + (RepoLookup::Failed, FallbackReason::LookupFailed), + ] { + let out = resolve_dash_target(WEB, Some("acme"), Ok("acme/other"), |_, _| lookup); + assert_eq!(out.url, "https://app.autter.dev/acme"); + assert_eq!(out.target, DashTarget::Org); + assert_eq!(out.fallback_reason, Some(reason)); + assert_eq!(out.candidate.as_deref(), Some("acme/other")); + } + } + + #[test] + fn dash_opens_the_app_dashboard_when_signed_out() { + let out = resolve_dash_target("https://app.autter.dev/", None, Ok("acme/api"), |_, _| { + panic!("no lookup when signed out") + }); + assert_eq!(out.url, "https://app.autter.dev/dashboard"); + assert_eq!(out.target, DashTarget::Home); + assert_eq!(out.fallback_reason, Some(FallbackReason::NotSignedIn)); + } + + #[test] + fn dash_urls_encode_segments_and_keep_staging_hosts() { assert_eq!( - build_personal_dashboard_url("https://app.autter.dev/"), - "https://app.autter.dev/me" + web_url("https://app.autter.dev/", &["acme"]), + "https://app.autter.dev/acme" ); - // Staging-style hosts keep their prefix. assert_eq!( - build_personal_dashboard_url("https://test-app.autter.dev"), - "https://test-app.autter.dev/me" + web_url( + "https://test-app.autter.dev", + &["acme", "repositories", "web app"] + ), + "https://test-app.autter.dev/acme/repositories/web%20app" + ); + assert_eq!( + web_url(WEB, &["a/b?c#d"]), + "https://app.autter.dev/a%2Fb%3Fc%23d" ); } #[test] - fn personal_dashboard_url_uses_app_host_not_api_host() { - let url = personal_dashboard_url(); - assert!( - url.ends_with("/me"), - "personal dashboard URL should end with /me, got {url}" - ); - // The opened URL must be derived from the web-app base, not the API base. - let expected = build_personal_dashboard_url(&crate::commands::login::web_app_url()); - assert_eq!(url, expected); - // With the default API base (https://api.autter.dev) the API-derived - // URL would be https://api.autter.dev/me (404); the web-app swap must - // have removed the `api` host label whenever one was present. - let api_base = crate::config::Config::fresh() - .api_base_url() - .trim_end_matches('/') - .to_string(); - if api_base.contains("api.") || api_base.contains("-api.") { - assert!( - !url.contains("api."), - "personal dashboard URL must not use the API host, got {url}" + fn dash_extracts_owner_and_name_from_remotes() { + for remote in [ + "https://github.com/Acme/api.git", + "git@github.com:Acme/api.git", + "ssh://git@github.com/Acme/api", + ] { + let normalized = crate::repo_url::normalize_repo_url(remote).unwrap(); + assert_eq!( + owner_and_name(&normalized).as_deref(), + Some("Acme/api"), + "{remote}" ); } + assert_eq!(owner_and_name("https://github.com/"), None); + assert_eq!(owner_and_name("https://github.com/solo"), None); + } + + #[test] + fn dash_matches_repositories_ignoring_case() { + let name = |wanted: &str| match_repository(wanted, &repos()).map(|repo| repo.name); + assert_eq!(name("acme/API").as_deref(), Some("api")); + assert_eq!(name("API").as_deref(), Some("api")); + assert_eq!(name("other/api"), None); + assert_eq!(name("missing"), None); + } + + #[test] + fn dash_reads_the_status_repository_list() { + let status = serde_json::json!({ + "repositories": [{ "name": "api", "fullName": "acme/api" }, { "name": 3 }], + "repository": null, + }); + assert_eq!( + connected_repositories(&status), + Some(vec![ConnectedRepo { + name: "api".into(), + full_name: "acme/api".into() + }]) + ); + assert_eq!( + connected_repositories(&serde_json::json!({ "error": "x" })), + None + ); + } + + #[test] + fn dash_json_report_shape() { + let resolution = resolve_dash_target(WEB, Some("acme"), Ok("acme/other"), |_, _| { + RepoLookup::NotConnected + }); + let json = serde_json::to_value(DashReport { + resolution: &resolution, + opened: false, + }) + .unwrap(); + assert_eq!( + json, + serde_json::json!({ + "url": "https://app.autter.dev/acme", + "target": "org", + "organization": "acme", + "repository": null, + "repository_full_name": null, + "fallback_reason": "repo_not_connected", + "opened": false, + }) + ); + assert_eq!( + fallback_message(&resolution).as_deref(), + Some("acme/other is not connected to acme; opening the organization dashboard.") + ); } }