Your own team of AI bots in one self-hosted binary: spaces, every account you have, handoffs, approvals and routines. Open-source, self-hosted alternative to Grok Bot, Claude Duet and OpenAI dots. Rust + React.
Rust ai-agentsai-assistantai-botautomationbotbots-teamchatbotclaude-duetgrokgrok-botgrok-bot-alternativeharnessllmmulti-agentopenai-dotsopenbotpersonal-agentrustself-hostedselfhosted-ai
Dev mode 0.7.1: detect the repo from team folders; on never 409s; new_reviews (#348)
Oleksandr Ivanchenko8c6d6b78f488
diff --git a/docs/dev-mode.md b/docs/dev-mode.mdindex 52df5dd4..56e99784 100644--- a/docs/dev-mode.md+++ b/docs/dev-mode.md@@ -1,8 +1,9 @@# Dev mode-Dev mode (0.7) points a space at one GitHub repo and branch. kwnt then reads the repo and turns what-happens there into cards. It writes to GitHub only when the person presses **Post to GitHub** on a-review card (0.7.1, see [Posting to GitHub](#posting-to-github)); nothing else is ever sent there.+Dev mode (0.7) points a space at one GitHub repo and branch, found in the space's team folders and+repo links. kwnt then reads the repo and turns what happens there into cards. It writes to GitHub+only when the person presses **Post to GitHub** on a review card (0.7.1, see+[Posting to GitHub](#posting-to-github)); nothing else is ever sent there.- **Landed**: one card per commit that reaches the watched branch, saying what changed and how risky it is.- **Review**: one card per open pull request head, with findings. The person can press **Fix it**@@ -44,6 +45,41 @@ See [Saved passwords](saved-passwords.md#approvals-off-needs-bitwarden) for why.`found`, `not_found` or `not_connected`. A new repo or branch starts the watch over. The same onekeeps its place.+### The repo comes from the space (0.7.1)++Turning Dev mode on never asks for a repo. kwnt goes through the space's teams in order and takes+each team's repo link, or else its folder when that folder is a git checkout. For a folder it reads+`git remote get-url origin` (or the first remote) and the default branch (`origin/HEAD`, else the+checked-out branch). It does this locally, with no network, no prompt and a 3 second limit. A+checkout with no remote is a `local` source. Two teams on the same repo count once. The user and+password part of a remote URL (`https://user:token@host/…`) is dropped before the URL is read, and+it is never logged, returned or stored.++`PUT {on: true}` with no `repo` watches the first detected source a GitHub connection can read. If+none can, or the space has none, Dev mode still turns on with no repo. The production floor and the+command guards work without one, and the poller waits. A watched repo stays watched when GitHub+fails to answer. A `repo` asked for that can't be read also turns Dev mode on, with no repo, and the+reply carries a `check` that says why. A `branch` the repo doesn't have is a 400.++`GET` (and the `PUT` reply) add:++- `sources`: `[{team, repo, host, from}]`. `from` is `repo` (the team's repo link), `folder` (its+ folder's remote) or `local`. `repo` is `owner/name` on GitHub and the whole path on other hosts. A+ `local` source has the folder's own name and no host. Folder paths are never returned.+- `status`:+ - `watching`: a repo is watched. While off, it means turning on would watch one.+ - `no_repo`: no team points at a git repo.+ - `not_connected`: there's a GitHub source, but no connection reads it. Once a GitHub connection+ is added or changed in Loose ends, every space that is on with no repo binds the repo it finds+ and polls soon, with no off and on. The `GET` does the same if nothing else did (at most every+ 30 s per space). A repo the person typed or picked is never replaced.+ - `other_host`: only GitLab, Gitea or other non-GitHub sources, or `local` ones. These are read+ from 0.7.2.+- `new_reviews`: review cards ready to read that were made since the desk was last opened (open+ ones only, never landed cards or floor approvals). A space never opened counts 0.+ `POST /api/spaces/:id/dev_mode/seen` marks the desk opened now (the same stored time as+ `POST …/dev/landed/seen`), so phone and desktop agree.+`GET /api/dev/cards/:id` returns one card of any kind, in the same shape as the lists, or 404. Thedesk reads a release notes draft here once its `dev_card` event says it is ready, since no listreturns those. A card in an archived space is refused like that space's lists.diff --git a/src/db/dev_mode.rs b/src/db/dev_mode.rsindex 585f881a..89f6f69e 100644--- a/src/db/dev_mode.rs+++ b/src/db/dev_mode.rs@@ -219,6 +219,25 @@ impl Database {Ok(self.dev_mode(space_id).await?.expect("just written"))}+ /// Binds a repo to a space that is on with none (plan any-git.md S3, QA B1), and only then: a+ /// space turned off or given a repo meanwhile is left as the person set it. True when bound.+ pub async fn bind_dev_repo(&self, space_id: &str, repo: &str, branch: &str, deploy_hint: Option<&str>) -> Result<bool, DbError> {+ let _writes = self.dev_on.writes.lock().await;+ let done = sqlx::query(+ "UPDATE dev_mode_spaces SET repo = ?2, branch = ?3, deploy_hint = ?4, last_seen_sha = NULL, polled_at = NULL,+ poll_error = NULL, updated_at = ?5+ WHERE space_id = ?1 AND on_ = 1 AND repo = ''",+ )+ .bind(space_id)+ .bind(repo)+ .bind(branch)+ .bind(deploy_hint)+ .bind(Utc::now())+ .execute(&self.pool)+ .await?;+ Ok(done.rows_affected() == 1)+ }+pub async fn dev_mode_polled(&self, space_id: &str, last_seen_sha: Option<&str>, error: Option<&str>) -> Result<(), DbError> {sqlx::query("UPDATE dev_mode_spaces SET last_seen_sha = COALESCE(?2, last_seen_sha), polled_at = ?3, poll_error = ?4 WHERE space_id = ?1").bind(space_id)diff --git a/src/server/auth.rs b/src/server/auth.rsindex 6ed3147f..73ca2a94 100644--- a/src/server/auth.rs+++ b/src/server/auth.rs@@ -887,6 +887,7 @@ mod tests {(&get, "/api/spaces/s1/dev_mode"),(&put, "/api/spaces/s1/dev_mode"),(&post, "/api/spaces/s1/dev_mode/check"),+ (&post, "/api/spaces/s1/dev_mode/seen"),(&get, "/api/spaces/s1/dev/landed?before=2026-11-05T00:00:00Z"),(&post, "/api/spaces/s1/dev/landed/seen"),(&get, "/api/spaces/s1/dev/reviews"),diff --git a/src/server/dev/poller.rs b/src/server/dev/poller.rsindex ad037edf..ed5b8226 100644--- a/src/server/dev/poller.rs+++ b/src/server/dev/poller.rs@@ -66,6 +66,16 @@ pub fn poll_soon(_state: &AppState, space_id: &str) {wake().notify_one();}+/// Whether `space_id` waits for the next wake, ahead of the timer.+pub fn is_due_soon(space_id: &str) -> bool {+ shared().lock().unwrap().soon.contains(space_id)+}++/// Takes `space_id` off the wake list; true when it was on it.+pub fn take_due_soon(space_id: &str) -> bool {+ shared().lock().unwrap().soon.remove(space_id)+}+/// The newest tag the last poll saw on the space's repo.pub fn last_tag(space_id: &str) -> Option<String> {shared().lock().unwrap().tags.get(space_id).map(|(t, _)| t.clone())@@ -164,6 +174,10 @@ pub async fn poll_logged(state: &AppState, row: DevModeRow) {/// One poll of one space. Merges are recorded as `last_seen_sha` one by one, so a failure part/// way keeps the ones done.pub async fn poll(state: &AppState, mode: &DevModeRow) -> Result<(), GhError> {+ // On with no repo (plan any-git.md S3): nothing to read, and nothing to report as an error+ if mode.repo.trim().is_empty() {+ return Ok(());+ }let space = SpaceId::new(&mode.space_id);let (client, _) = repo::client_for(state, &mode.repo).await?;let kwants = state.db.list_kwants(&space).await.unwrap_or_default();diff --git a/src/server/dev/repo.rs b/src/server/dev/repo.rsindex e21a4f44..ef60f6b2 100644--- a/src/server/dev/repo.rs+++ b/src/server/dev/repo.rs@@ -133,16 +133,23 @@ pub async fn client_for(state: &AppState, repo: &str) -> Result<(GithubSource, cErr(last)}-/// The repo a space's teams point at, normalised: the first team whose `repo_url` reads.+/// The repo a space's teams point at, as `owner/name`: the first detected source on a GitHub+/// host (see [`detect`]).pub async fn prefill(state: &AppState, space: &SpaceId) -> Option<String> {- let teams = state.db.list_teams(space).await.ok()?;- teams.iter().filter_map(|t| t.repo_url.as_deref()).find_map(normalize).map(|(_, r)| r)+ let hosts = github_hosts(state).await;+ detect(state, space).await.into_iter().find(|s| s.on_github(&hosts)).map(|s| s.repo)}-/// Checks `input` (or the team's repo when it's empty). `Err` is a GitHub failure that is-/// neither found nor not found (a rate limit, GitHub down): the route answers 502 with it.+/// Checks `input` (or the first detected GitHub source when it's empty). `Err` is a GitHub+/// failure that is neither found nor not found (a rate limit, GitHub down): the route answers+/// 502 with it.pub async fn check(state: &AppState, space: &SpaceId, input: &str) -> Result<Check, String> {- let input = if input.trim().is_empty() { prefill(state, space).await.unwrap_or_default() } else { input.to_string() };+ let input = if input.trim().is_empty() {+ let hosts = github_hosts(state).await;+ detect(state, space).await.into_iter().find(|s| s.on_github(&hosts)).map(|s| s.check_input()).unwrap_or_default()+ } else {+ strip_userinfo(input)+ };let Some((host, repo)) = normalize(&input) else {return Ok(Check::of("not_found", None));};@@ -179,6 +186,260 @@ pub async fn check(state: &AppState, space: &SpaceId, input: &str) -> Result<CheOk(answer)}+// ---------------------------------------------------------------------------------------------+// Detection (plan any-git.md S1, S2): the repos a space's teams already point at, from each team's+// repo link or else its folder's git remote. Nothing here touches the network, and no URL leaves+// [`parse_remote`] with its userinfo.++/// A repo one of the space's teams points at. Serialised as `{team, repo, host, from}`: the team's+/// name, never its folder.+#[derive(Debug, Clone, Serialize, PartialEq)]+pub struct Source {+ pub team: String,+ /// `owner/name` on a GitHub host, the whole path (`group/sub/name`) on another host, and the+ /// folder's own name for a `local` source.+ pub repo: String,+ /// `github.com`, `gitlab.example.com`; `null` for a `local` source.+ pub host: Option<String>,+ /// `repo` (the team's repo link), `folder` (its folder's git remote) or `local` (a git folder+ /// with no remote).+ pub from: &'static str,+ /// The folder's default branch (`refs/remotes/<remote>/HEAD`, else the checked-out one).+ #[serde(skip)]+ pub branch: Option<String>,+ /// What dedupes sources: `host/repo` lowercased, or the folder for a `local` one.+ #[serde(skip)]+ key: String,+}++impl Source {+ /// Whether this source is on GitHub (github.com, or the web host of a GitHub Enterprise+ /// connection in `hosts`).+ pub fn on_github(&self, hosts: &[String]) -> bool {+ self.host.as_deref().is_some_and(|h| hosts.iter().any(|g| g == h))+ }++ /// What [`check`] takes for this source: `host/owner/name`.+ pub fn check_input(&self) -> String {+ match &self.host {+ Some(h) => format!("{h}/{}", self.repo),+ None => self.repo.clone(),+ }+ }+}++/// `url` without its userinfo: `https://user:token@host/p` → `https://host/p`,+/// `git@host:p` → `host:p`. Anything else comes back as it was.+pub fn strip_userinfo(url: &str) -> String {+ let s = url.trim();+ // Everything up to the last `@` is userinfo: a token with a `/` in it can't hide past it+ let (scheme, rest) = match s.find("://") {+ Some(i) => s.split_at(i + 3),+ None => ("", s),+ };+ let end = rest.find(['?', '#']).unwrap_or(rest.len());+ match rest[..end].rfind('@') {+ Some(at) => format!("{scheme}{}", &rest[at + 1..]),+ None => s.to_string(),+ }+}++/// `(host, path)` of a git remote URL (`https://`, `ssh://`, `git://`, `git+https://` or scp-like+/// `git@host:path`), its userinfo dropped first, the host lowercased without `www.` and the path+/// without `.git`. `None` for a local path or anything that isn't a repo path.+pub fn parse_remote(raw: &str) -> Option<(String, String)> {+ let s = strip_userinfo(raw);+ if s.is_empty() || s.len() > 500 || s.chars().any(|c| c.is_whitespace() || c.is_control()) {+ return None;+ }+ let (host, path) = if let Some(i) = s.find("://") {+ let scheme = s[..i].to_ascii_lowercase();+ let scheme = scheme.strip_prefix("git+").unwrap_or(&scheme);+ if !matches!(scheme, "https" | "http" | "ssh" | "git") {+ return None;+ }+ let url = url::Url::parse(&format!("{scheme}{}", &s[i..])).ok()?;+ (url.host_str()?.to_string(), url.path().to_string())+ } else {+ let (h, p) = s.split_once(':')?;+ // `./x:y`, `/srv/x:y` and `C:\\x` are paths, not hosts+ if h.is_empty() || h.len() == 1 || !h.chars().all(|c| c.is_ascii_alphanumeric() || "-.".contains(c)) {+ return None;+ }+ (h.to_string(), p.to_string())+ };+ let host = host.to_ascii_lowercase();+ let host = host.strip_prefix("www.").unwrap_or(&host).to_string();+ let path = path.trim_matches('/');+ let path = path.strip_suffix(".git").unwrap_or(path);+ let segs: Vec<&str> = path.split('/').collect();+ let ok = |p: &str| !p.is_empty() && p != "." && p != ".." && !p.starts_with('-') && p.len() <= 100 && p.chars().all(|c| c.is_ascii_alphanumeric() || "-_.".contains(c));+ if host.is_empty() || segs.len() < 2 || segs.len() > 20 || !segs.iter().all(|p| ok(p)) {+ return None;+ }+ Some((host, segs.join("/")))+}++/// `(host, repo)` of what a team's repo link or folder remote says: `owner/name` on a GitHub+/// host in `gh_hosts`, the whole path on any other. In a repo link (`shorthand`), a plain+/// `owner/name` is github.com's; to git, that's a folder.+fn source_repo(raw: &str, gh_hosts: &[String], shorthand: bool) -> Option<(String, String)> {+ let (host, path) = match parse_remote(raw) {+ Some(hp) => hp,+ None if !shorthand => return None,+ None => {+ // `owner/name`, `github.com/owner/name`: [`normalize`] reads those (it refuses userinfo)+ let (host, repo) = normalize(&strip_userinfo(raw))?;+ let host = host.unwrap_or_else(|| "github.com".into());+ (host.strip_prefix("www.").unwrap_or(&host).to_string(), repo)+ }+ };+ if gh_hosts.contains(&host) {+ // GitHub URLs go on past the repo (`/tree/main`, `/pull/3`)+ let mut it = path.split('/');+ let (o, n) = (it.next()?, it.next()?);+ return Some((host, format!("{o}/{n}")));+ }+ Some((host, path))+}++/// The web hosts of GitHub repos: github.com, and each GitHub connection's Enterprise host. Reads+/// the connections' settings only, not their tokens.+pub async fn github_hosts(state: &AppState) -> Vec<String> {+ let mut hosts = vec!["github.com".to_string()];+ for row in state.db.zombie_sources().await.unwrap_or_default().into_iter().filter(|r| r.kind == "github") {+ if let Ok(cfg) = serde_json::from_str::<GithubConfig>(&row.config) {+ let h = web_host(&cfg);+ if !h.is_empty() && !hosts.contains(&h) {+ hosts.push(h);+ }+ }+ }+ hosts+}++/// How long one git command in a team folder may take.+const GIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(3);++/// `git -C dir args…`, local only: no prompt, no fsmonitor hook, no walking up out of `dir`, and+/// killed after [`GIT_TIMEOUT`]. Its trimmed stdout on success. Its stderr is dropped unread, so+/// a URL in an error never reaches a log.+async fn git(dir: &std::path::Path, args: &[&str]) -> Option<String> {+ let mut cmd = tokio::process::Command::new("git");+ cmd.arg("-C").arg(dir).args(["-c", "core.fsmonitor=false"]).args(args);+ for v in ["GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_CONFIG_PARAMETERS", "GIT_CONFIG_COUNT"] {+ cmd.env_remove(v);+ }+ cmd.env("GIT_TERMINAL_PROMPT", "0").env("GIT_OPTIONAL_LOCKS", "0");+ if let Some(parent) = dir.parent() {+ cmd.env("GIT_CEILING_DIRECTORIES", parent);+ }+ cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::null()).kill_on_drop(true);+ let out = tokio::time::timeout(GIT_TIMEOUT, cmd.output()).await.ok()?.ok()?;+ let text = String::from_utf8_lossy(&out.stdout).trim().to_string();+ (out.status.success() && !text.is_empty()).then_some(text)+}++/// What a team folder's git says: its remote's URL (`origin`, else the first remote; `None` when+/// it has none) and its default branch. `None` when the folder isn't a git checkout.+pub async fn read_folder(dir: &std::path::Path) -> Option<(Option<String>, Option<String>)> {+ if !dir.join(".git").exists() {+ return None;+ }+ // A folder git can't open (dubious ownership, a broken .git) counts as no checkout+ git(dir, &["rev-parse", "--git-dir"]).await?;+ let remotes = git(dir, &["remote"]).await.unwrap_or_default();+ let names: Vec<&str> = remotes.lines().map(str::trim).filter(|l| !l.is_empty()).collect();+ let remote = names.iter().find(|n| **n == "origin").or(names.first()).copied();+ let url = match remote {+ Some(r) => git(dir, &["remote", "get-url", "--", r]).await,+ None => None,+ };+ let mut branch = None;+ if let Some(r) = remote {+ let head = format!("refs/remotes/{r}/HEAD");+ if let Some(b) = git(dir, &["symbolic-ref", "--quiet", "--short", &head]).await {+ branch = b.strip_prefix(&format!("{r}/")).map(str::to_string).or(Some(b));+ }+ }+ if branch.is_none() {+ branch = git(dir, &["symbolic-ref", "--quiet", "--short", "HEAD"]).await;+ }+ Some((url, branch.filter(|b| super::routes::valid_branch(b))))+}++/// One team as detection reads it: its name, folder setting and repo link.+pub struct TeamRef<'a> {+ pub name: &'a str,+ pub workspace_path: Option<&'a str>,+ pub repo_url: Option<&'a str>,+}++/// The sources of `teams`, in team order, deduped by repo (case-insensitive): each team's repo+/// link, or else its folder (`tools::team_workspace_path` under `space_dir`) when that is a git+/// checkout. `gh_hosts` are the hosts whose repos are `owner/name` (see [`github_hosts`]).+pub async fn detect_teams(teams: &[TeamRef<'_>], space_dir: &std::path::Path, gh_hosts: &[String]) -> Vec<Source> {+ let mut out: Vec<Source> = Vec::new();+ for t in teams {+ let link = t.repo_url.map(str::trim).filter(|s| !s.is_empty());+ let folder = crate::tools::team_workspace_path(space_dir, t.name, t.workspace_path, link);+ let read = read_folder(&folder).await;+ let branch = read.as_ref().and_then(|(_, b)| b.clone());+ let found = if let Some((host, repo)) = link.and_then(|l| source_repo(l, gh_hosts, true)) {+ Some((Some(host), repo, "repo"))+ } else if let Some((url, _)) = &read {+ match url.as_deref().and_then(|u| source_repo(u, gh_hosts, false)) {+ Some((host, repo)) => Some((Some(host), repo, "folder")),+ // A checkout with no remote, or one that isn't a URL (another folder)+ None => folder.file_name().map(|n| (None, n.to_string_lossy().to_string(), "local")),+ }+ } else {+ None+ };+ let Some((host, repo, from)) = found else { continue };+ let key = match &host {+ Some(h) => format!("{h}/{repo}").to_lowercase(),+ None => format!("local:{}", std::fs::canonicalize(&folder).unwrap_or(folder.clone()).display()),+ };+ if out.iter().any(|s| s.key == key) {+ continue;+ }+ out.push(Source { team: t.name.to_string(), repo, host, from, branch, key });+ }+ out+}++/// The repos `space`'s teams already point at, in team order (plan any-git.md S1).+pub async fn detect(state: &AppState, space: &SpaceId) -> Vec<Source> {+ let teams = state.db.list_teams(space).await.unwrap_or_default();+ let refs: Vec<TeamRef> = teams.iter().map(|t| TeamRef { name: &t.name, workspace_path: t.workspace_path.as_deref(), repo_url: t.repo_url.as_deref() }).collect();+ let dir = crate::db::spaces::space_data_dir(&state.config.data_dir, space);+ detect_teams(&refs, &dir, &github_hosts(state).await).await+}++/// The desk's line (plan any-git.md S4), from whether Dev mode is on, the watched repo (`""`:+/// none), the detected sources and whether a GitHub connection exists:+/// - `watching`: a repo is watched (or, while off, would be: a GitHub source and a connection);+/// - `no_repo`: no team points at a git repo;+/// - `not_connected`: a GitHub source that no connection reads;+/// - `other_host`: only non-GitHub or `local` sources, read from 0.7.2.+pub fn status(on: bool, watched: &str, sources: &[Source], gh_hosts: &[String], connected: bool) -> &'static str {+ if !watched.is_empty() {+ "watching"+ } else if sources.is_empty() {+ "no_repo"+ } else if sources.iter().any(|s| s.on_github(gh_hosts)) {+ // On with no repo means switching on found none a connection reads+ if !on && connected {+ "watching"+ } else {+ "not_connected"+ }+ } else {+ "other_host"+ }+}+#[cfg(test)]mod tests {use super::*;@@ -246,4 +507,184 @@ mod tests {assert_eq!(deploy_hint(&v(&["dockerfile"])), Some("docker"));assert_eq!(deploy_hint(&v(&["README.md", "src/"])), None);}++ // ---- Detection (plan any-git.md S1, S2): throwaway repos, no network ----------------------++ fn fake_token() -> String {+ // Built at runtime so no scanner flags the source+ ["gh", "p_", "JUNOFAKE", "0123456789abcdefghijklmnopqrstuv"].concat()+ }++ fn sh_git(dir: &std::path::Path, args: &[&str]) {+ let ok = std::process::Command::new("git").arg("-C").arg(dir).args(args).env("GIT_TERMINAL_PROMPT", "0").output().unwrap();+ assert!(ok.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&ok.stderr));+ }++ /// A `git init` checkout in `root/name` on `branch`, with these remotes.+ fn checkout(root: &std::path::Path, name: &str, branch: &str, remotes: &[(&str, &str)]) -> std::path::PathBuf {+ let dir = root.join(name);+ std::fs::create_dir_all(&dir).unwrap();+ sh_git(&dir, &["init", "-q", "-b", branch]);+ for (n, url) in remotes {+ sh_git(&dir, &["remote", "add", n, url]);+ }+ dir+ }++ fn team<'a>(name: &'a str, folder: Option<&'a str>, link: Option<&'a str>) -> TeamRef<'a> {+ TeamRef { name, workspace_path: folder, repo_url: link }+ }++ fn gh() -> Vec<String> {+ vec!["github.com".into()]+ }++ /// A source as `(team, repo, host, from, branch)`, for comparing in one assert.+ type Brief = (String, String, Option<String>, &'static str, Option<String>);++ fn brief(s: &[Source]) -> Vec<Brief> {+ s.iter().map(|s| (s.team.clone(), s.repo.clone(), s.host.clone(), s.from, s.branch.clone())).collect()+ }++ #[test]+ fn userinfo_is_stripped_before_parsing() {+ let t = fake_token();+ assert_eq!(strip_userinfo(&format!("https://x-access-token:{t}@github.com/o/r.git")), "https://github.com/o/r.git");+ assert_eq!(strip_userinfo(&format!("https://{t}@github.com/o/r")), "https://github.com/o/r");+ assert_eq!(strip_userinfo("[email protected]:o/r.git"), "github.com:o/r.git");+ assert_eq!(strip_userinfo(&format!("ssh://git:{t}@gitlab.example.com:2222/g/r.git")), "ssh://gitlab.example.com:2222/g/r.git");+ // A token with a `/` in it can't push its tail past the host+ assert_eq!(strip_userinfo("https://u:ab/[email protected]/o/r"), "https://host.example/o/r");+ assert_eq!(strip_userinfo("https://github.com/o/r"), "https://github.com/o/r");+ }++ #[test]+ fn remotes_parse_to_host_and_path() {+ let p = |s: &str| parse_remote(s).map(|(h, p)| format!("{h} {p}"));+ let t = fake_token();+ assert_eq!(p("https://github.com/demo-org/app.git").as_deref(), Some("github.com demo-org/app"));+ assert_eq!(p(&format!("https://x-access-token:{t}@github.com/demo-org/app.git")).as_deref(), Some("github.com demo-org/app"));+ assert_eq!(p("[email protected]:demo-org/app.git").as_deref(), Some("github.com demo-org/app"));+ assert_eq!(p("ssh://[email protected]/demo-org/app.git").as_deref(), Some("github.com demo-org/app"));+ assert_eq!(p("ssh://[email protected]:2222/group/sub/app.git").as_deref(), Some("gitlab.example.com group/sub/app"));+ assert_eq!(p("git+https://www.github.com/demo-org/app").as_deref(), Some("github.com demo-org/app"));+ assert_eq!(p("http://127.0.0.1:9495/demo-org/app.git").as_deref(), Some("127.0.0.1 demo-org/app"));+ assert_eq!(p("codeberg.org:me/app.git").as_deref(), Some("codeberg.org me/app"));+ for bad in ["/srv/git/app.git", "./app", "../app.git", "file:///srv/app.git", "C:\\repos\\app", "https://github.com/onlyowner", "", "git@host:o/r; rm -rf /"] {+ assert_eq!(parse_remote(bad), None, "{bad:?}");+ }+ // GitHub repos are `owner/name` even when the link goes on; other hosts keep the path+ assert_eq!(source_repo("https://github.com/o/r/tree/main", &gh(), true), Some(("github.com".into(), "o/r".into())));+ assert_eq!(source_repo("o/r", &gh(), true), Some(("github.com".into(), "o/r".into())));+ assert_eq!(source_repo("github.com/o/r", &gh(), true), Some(("github.com".into(), "o/r".into())));+ assert_eq!(source_repo("https://gitlab.com/g/sub/r", &gh(), true), Some(("gitlab.com".into(), "g/sub/r".into())));+ let ghe = vec!["github.com".to_string(), "ghe.example.com".to_string()];+ assert_eq!(source_repo("[email protected]:team/app.git", &ghe, true), Some(("ghe.example.com".into(), "team/app".into())));+ // To git, `owner/name` is a folder+ assert_eq!(source_repo("o/r", &gh(), false), None);+ }++ #[tokio::test]+ async fn folders_are_read_by_their_git_remote() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ let t = fake_token();+ let https = checkout(root, "https", "main", &[("origin", &format!("https://x-access-token:{t}@github.com/Demo-Org/App.git"))]);+ let scp = checkout(root, "scp", "main", &[("origin", "[email protected]:demo-org/scp-app.git")]);+ let ssh = checkout(root, "ssh", "trunk", &[("origin", "ssh://[email protected]/group/sub/app.git")]);+ // No `origin`: the first remote+ let other = checkout(root, "other", "dev", &[("upstream", "https://codeberg.org/me/thing.git")]);+ // origin/HEAD names the default branch over the checked-out one+ sh_git(&scp, &["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/release"]);+ let (s1, s2, s3, s4) = (https.to_string_lossy(), scp.to_string_lossy(), ssh.to_string_lossy(), other.to_string_lossy());+ let teams = [team("Web", Some(&s1), None), team("Api", Some(&s2), None), team("Ops", Some(&s3), None), team("Docs", Some(&s4), None)];+ let got = detect_teams(&teams, root, &gh()).await;+ let gh_ = Some("github.com".to_string());+ assert_eq!(+ brief(&got),+ vec![+ ("Web".into(), "Demo-Org/App".into(), gh_.clone(), "folder", Some("main".into())),+ ("Api".into(), "demo-org/scp-app".into(), gh_, "folder", Some("release".into())),+ ("Ops".into(), "group/sub/app".into(), Some("gitlab.example.com".into()), "folder", Some("trunk".into())),+ ("Docs".into(), "me/thing".into(), Some("codeberg.org".into()), "folder", Some("dev".into())),+ ]+ );+ assert!(got[0].on_github(&gh()) && !got[2].on_github(&gh()));+ let out = serde_json::to_string(&got).unwrap();+ assert!(!out.contains(&t), "the token left the parser: {out}");+ assert!(!out.contains(&*root.to_string_lossy()), "a folder path is in the reply: {out}");+ assert!(!out.contains("branch") && !out.contains("key"), "only team, repo, host, from: {out}");+ }++ #[tokio::test]+ async fn plain_folders_and_remoteless_checkouts() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ let plain = root.join("plain");+ std::fs::create_dir_all(&plain).unwrap();+ // A folder inside someone else's checkout is not a checkout itself+ let outer = checkout(root, "outer", "main", &[("origin", "https://github.com/o/outer.git")]);+ let inner = outer.join("inner");+ std::fs::create_dir_all(&inner).unwrap();+ let local = checkout(root, "notes", "draft", &[]);+ // A remote that is another folder counts as local too+ let mirror = checkout(root, "mirror", "main", &[("origin", "/srv/git/mirror.git")]);+ let (p, i, l, m) = (plain.to_string_lossy(), inner.to_string_lossy(), local.to_string_lossy(), mirror.to_string_lossy());+ let missing = root.join("gone").to_string_lossy().to_string();+ let teams = [team("Plain", Some(&p), None), team("Inner", Some(&i), None), team("Gone", Some(&missing), None), team("Notes", Some(&l), None), team("Mirror", Some(&m), None)];+ let got = detect_teams(&teams, root, &gh()).await;+ assert_eq!(brief(&got), vec![("Notes".into(), "notes".into(), None, "local", Some("draft".into())), ("Mirror".into(), "mirror".into(), None, "local", Some("main".into()))]);+ // An empty space has nothing+ assert!(detect_teams(&[], root, &gh()).await.is_empty());+ // A team with no folder setting uses the space's shared folder (`<space>/workspace`)+ let shared = checkout(root, "workspace", "main", &[("origin", "[email protected]:o/shared.git")]);+ assert!(shared.ends_with("workspace"));+ assert_eq!(brief(&detect_teams(&[team("Any", None, None)], root, &gh()).await), vec![("Any".into(), "o/shared".into(), Some("github.com".into()), "folder", Some("main".into()))]);+ }++ #[tokio::test]+ async fn sources_dedupe_by_repo_and_keep_team_order() {+ let tmp = tempfile::tempdir().unwrap();+ let root = tmp.path();+ let a = checkout(root, "a", "main", &[("origin", "https://github.com/demo-org/app.git")]);+ let b = checkout(root, "b", "main", &[("origin", "[email protected]:DEMO-ORG/APP.git")]);+ let c = checkout(root, "c", "main", &[("origin", "https://github.com/demo-org/site.git")]);+ let (a, b, c) = (a.to_string_lossy(), b.to_string_lossy(), c.to_string_lossy());+ // Two teams on one repo: the first names it+ let got = detect_teams(&[team("First", Some(&a), None), team("Second", Some(&b), None)], root, &gh()).await;+ assert_eq!(got.iter().map(|s| s.team.as_str()).collect::<Vec<_>>(), ["First"]);+ // Two repos: both, in team order+ let got = detect_teams(&[team("Site", Some(&c), None), team("App", Some(&a), None)], root, &gh()).await;+ assert_eq!(got.iter().map(|s| (s.team.as_str(), s.repo.as_str())).collect::<Vec<_>>(), [("Site", "demo-org/site"), ("App", "demo-org/app")]);+ // A repo link wins over the folder, and a link to the same repo as a folder dedupes+ let t = fake_token();+ let link = format!("https://bot:{t}@github.com/demo-org/linked");+ let got = detect_teams(&[team("Linked", Some(&c), Some(&link)), team("App", Some(&a), Some("demo-org/app")), team("Again", Some(&a), None)], root, &gh()).await;+ assert_eq!(+ brief(&got),+ vec![("Linked".into(), "demo-org/linked".into(), Some("github.com".into()), "repo", Some("main".into())), ("App".into(), "demo-org/app".into(), Some("github.com".into()), "repo", Some("main".into()))]+ );+ assert!(!format!("{got:?}").contains(&t), "the token reached a Source");+ // Two local folders are two sources; the same folder twice is one+ let n = checkout(root, "n", "main", &[]).to_string_lossy().to_string();+ let got = detect_teams(&[team("X", Some(&n), None), team("Y", Some(&n), None)], root, &gh()).await;+ assert_eq!(got.len(), 1);+ }++ #[test]+ fn the_status_says_what_the_desk_shows() {+ let src = |host: Option<&str>| Source { team: "T".into(), repo: "o/r".into(), host: host.map(str::to_string), from: "folder", branch: None, key: String::new() };+ let github = [src(Some("github.com"))];+ let gitlab = [src(Some("gitlab.com")), src(None)];+ assert_eq!(status(true, "o/r", &github, &gh(), false), "watching");+ assert_eq!(status(true, "", &[], &gh(), false), "no_repo");+ assert_eq!(status(false, "", &[], &gh(), true), "no_repo");+ assert_eq!(status(true, "", &github, &gh(), true), "not_connected", "on with no repo: no connection read it");+ assert_eq!(status(false, "", &github, &gh(), false), "not_connected");+ assert_eq!(status(false, "", &github, &gh(), true), "watching", "off: turning on would watch it");+ assert_eq!(status(true, "", &gitlab, &gh(), true), "other_host");+ // A GitHub Enterprise host is GitHub+ let ghe = vec!["github.com".to_string(), "gitlab.com".to_string()];+ assert_eq!(status(true, "", &gitlab, &ghe, false), "not_connected");+ }}diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rsindex d547c8d4..5aa31059 100644--- a/src/server/dev/routes.rs+++ b/src/server/dev/routes.rs@@ -41,16 +41,21 @@ async fn guard(state: &AppState, headers: &HeaderMap, id: &str) -> Result<SpaceI// ---------------------------------------------------------------------------------------------// Settings-/// `GET /api/spaces/:id/dev_mode` reply. With no row yet: off, the team's repo as a prefill.+/// `GET /api/spaces/:id/dev_mode` reply. With no row yet: off, the first detected GitHub repo as+/// a prefill. Always with the detected `sources` and the desk's `status` (plan any-git.md S4).#[allow(clippy::result_large_err)]pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Response> {+ // On with no repo and a connection now: bind the detected repo before answering (QA B1)+ bind_on_read(state, space).await;let row = state.db.dev_mode(space.as_str()).await.map_err(internal)?;let calls = state.db.dev_calls_today(space.as_str()).await.map_err(internal)?;- let mut v = match row {- Some(r) => row_json(&r, calls),+ let sources = repo::detect(state, space).await;+ let hosts = repo::github_hosts(state).await;+ let mut v = match &row {+ Some(r) => row_json(r, calls),None => json!({"on": false,- "repo": repo::prefill(state, space).await,+ "repo": sources.iter().find(|s| s.on_github(&hosts)).map(|s| s.repo.clone()),"branch": null,"deploy_hint": null,"backup_command": null,@@ -61,6 +66,7 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo"calls_cap": super::call_cap(),}),};+ with_sources(state, row.as_ref(), sources, &hosts, &mut v).await;// Where a review would be posted, and as whom (post-to-github.md P7 and its amendment)let has_repo = v["repo"].as_str().is_some_and(|r| !r.is_empty());let (forge, login) = super::post::forge_json(state, has_repo).await;@@ -69,6 +75,35 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, RespoOk(v)}+/// Adds `sources` (`[{team, repo, host, from}]`, no paths) and `status` to a settings reply.+async fn with_sources(state: &AppState, row: Option<&DevModeRow>, sources: Vec<repo::Source>, hosts: &[String], v: &mut Value) {+ let on = row.is_some_and(|r| r.on);+ let watched = row.map(|r| r.repo.as_str()).unwrap_or("");+ // Only while off with nothing watched does the answer hang on a connection existing+ let ask = !on && watched.is_empty() && sources.iter().any(|s| s.on_github(hosts));+ let connected = ask && repo::clients(state).await.is_ok();+ v["status"] = json!(repo::status(on, watched, &sources, hosts, connected));+ v["sources"] = json!(sources);+ v["new_reviews"] = json!(new_reviews(state, row).await);+}++/// Review cards ready to read that were made after the person last opened the desk (plan+/// user-flow.md F6): the open ones only (newest of each PR, not stale), never landed cards or+/// floor approvals. A space that was never seen counts nothing, so an update shows no surprise+/// badge.+async fn new_reviews(state: &AppState, row: Option<&DevModeRow>) -> usize {+ let Some((space, seen)) = row.and_then(|r| Some((r.space_id.as_str(), r.seen_at?))) else {+ return 0;+ };+ match open_reviews(state, &SpaceId::new(space)).await {+ Ok(rows) => rows.iter().filter(|r| r.status == READY && r.created_at > seen).count(),+ Err(e) => {+ tracing::warn!("dev: {e}");+ 0+ }+ }+}+fn row_json(r: &DevModeRow, calls: i64) -> Value {json!({"on": r.on,@@ -146,6 +181,83 @@ pub fn valid_branch(b: &str) -> bool {&& b.chars().all(|c| !c.is_control() && !c.is_whitespace() && !"~^:?*[\\".contains(c))}+/// How often a GET may try to bind a detected repo for one space (the source hooks don't wait).+const BIND_COOLDOWN: std::time::Duration = std::time::Duration::from_secs(30);++fn bind_tried() -> &'static std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>> {+ static T: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, std::time::Instant>>> = std::sync::OnceLock::new();+ T.get_or_init(Default::default)+}++/// A space that is on with no repo watches the first detected GitHub source a connection now+/// reads, the same choice as turning on, and the poller wakes (QA B1: a GitHub connection added+/// while on). A space off, or with a repo, is never touched. True when a repo was bound.+pub async fn bind_detected(state: &AppState, space: &SpaceId) -> bool {+ let Ok(Some(row)) = state.db.dev_mode(space.as_str()).await else { return false };+ if !row.on || !row.repo.is_empty() {+ return false;+ }+ bind_tried().lock().unwrap().insert(space.as_str().to_string(), std::time::Instant::now());+ let hosts = repo::github_hosts(state).await;+ let mut seen: Vec<String> = Vec::new();+ for s in repo::detect(state, space).await.into_iter().filter(|s| s.on_github(&hosts)) {+ let key = s.check_input().to_lowercase();+ if seen.contains(&key) {+ continue;+ }+ seen.push(key);+ let Ok(found) = repo::check(state, space, &s.check_input()).await else { continue };+ if found.state != "found" {+ continue;+ }+ let full = found.repo.clone().unwrap_or_default();+ let default = found.branch.clone().unwrap_or_else(|| "main".into());+ // The branch the space already names (a folder's or the person's) when the repo has it+ let branch = match row.branch.trim() {+ b if b.is_empty() || b == default => default.clone(),+ b => match repo::client_for(state, &full).await {+ Ok((c, _)) if matches!(c.dev_branch_exists(&full, b).await, Ok(true)) => b.to_string(),+ _ => default.clone(),+ },+ };+ return match state.db.bind_dev_repo(space.as_str(), &full, &branch, found.deploy_hint).await {+ Ok(true) => {+ tracing::info!(space = %space, repo = %full, branch = %branch, "dev: bound the detected repo");+ poller::poll_soon(state, space.as_str());+ true+ }+ Ok(false) => false,+ Err(e) => {+ tracing::warn!("dev: {e}");+ false+ }+ };+ }+ false+}++/// [`bind_detected`] for every space that is on with no repo: after a GitHub source is added or+/// changed.+pub async fn bind_detected_all(state: &AppState) {+ for row in state.db.dev_mode_on_spaces().await.unwrap_or_default().into_iter().filter(|r| r.repo.is_empty()) {+ bind_detected(state, &SpaceId::new(&row.space_id)).await;+ }+}++/// The GET fallback: on, no repo, a GitHub source detected and a connection there, at most once+/// per [`BIND_COOLDOWN`] for the space.+async fn bind_on_read(state: &AppState, space: &SpaceId) -> bool {+ let Ok(Some(row)) = state.db.dev_mode(space.as_str()).await else { return false };+ if !row.on || !row.repo.is_empty() {+ return false;+ }+ let recent = bind_tried().lock().unwrap().get(space.as_str()).is_some_and(|t| t.elapsed() < BIND_COOLDOWN);+ if recent || repo::clients(state).await.is_err() {+ return false;+ }+ bind_detected(state, space).await+}+pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id): Path<String>, Json(body): Json<PutBody>) -> Response {let space = match guard(&state, &headers, &id).await {Ok(s) => s,@@ -171,36 +283,84 @@ pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(idreturn error(StatusCode::BAD_REQUEST, "that isn't a branch name");}}- let asked_repo = body.repo.as_deref().map(str::trim).filter(|r| !r.is_empty());+ // Any user:token@ part of a typed URL is dropped before it is read or kept (plan any-git.md S2)+ let asked_owned = body.repo.as_deref().map(repo::strip_userinfo);+ let asked_repo = asked_owned.as_deref().map(str::trim).filter(|r| !r.is_empty());let kept_repo = before.as_ref().map(|r| r.repo.clone()).filter(|r| !r.is_empty());+ let asked_branch = body.branch.as_deref().map(str::trim).filter(|b| !b.is_empty());+ let sources = repo::detect(&state, &space).await;+ let hosts = repo::github_hosts(&state).await;+ let mut asked_check = None;let (repo_name, branch, hint) = if body.on {- // Turning on (or staying on) needs a repo GitHub finds, through the person's connection- let input = asked_repo.map(str::to_string).or(kept_repo.clone()).unwrap_or_default();- let found = match repo::check(&state, &space, &input).await {- Ok(c) => c,- Err(e) => return error(StatusCode::BAD_GATEWAY, e),- };- if found.state != "found" {- return (StatusCode::CONFLICT, Json(json!({"error": "Dev mode needs a repo kwant can read", "check": found}))).into_response();+ // Turning on always works (plan any-git.md S3): the repo asked for, else the one watched,+ // else the first detected source a connection reads. With none, it's on with no repo.+ let kept_on = before.as_ref().filter(|b| b.on && !b.repo.is_empty() && asked_repo.is_none_or(|a| repo::normalize(a).is_some_and(|(_, n)| n.eq_ignore_ascii_case(&b.repo))));+ let mut candidates: Vec<String> = Vec::new();+ if let Some(a) = asked_repo {+ candidates.push(a.to_string());+ } else if let Some(b) = kept_on {+ candidates.push(b.repo.clone());+ } else {+ candidates.extend(kept_repo.clone());+ candidates.extend(sources.iter().filter(|s| s.on_github(&hosts)).map(|s| s.check_input()));}- let full = found.repo.clone().unwrap_or_default();- let same_repo = before.as_ref().is_some_and(|r| r.repo.eq_ignore_ascii_case(&full));- let branch = match body.branch.as_deref().map(str::trim).filter(|b| !b.is_empty()) {- Some(b) => b.to_string(),- None if same_repo && !before.as_ref().unwrap().branch.is_empty() => before.as_ref().unwrap().branch.clone(),- None => found.branch.clone().unwrap_or_else(|| "main".into()),- };- if Some(&branch) != found.branch.as_ref() {- match repo::client_for(&state, &full).await {- Ok((c, _)) => match c.dev_branch_exists(&full, &branch).await {- Ok(true) => {}- Ok(false) => return error(StatusCode::CONFLICT, format!("{full} has no branch {branch}")),+ let mut found = None;+ let mut unanswered = None;+ let mut seen: Vec<String> = Vec::new();+ for c in candidates {+ let key = repo::normalize(&c).map(|(_, n)| n.to_lowercase()).unwrap_or_default();+ if !key.is_empty() && seen.contains(&key) {+ continue;+ }+ seen.push(key);+ match repo::check(&state, &space, &c).await {+ Ok(ch) if ch.state == "found" => {+ found = Some(ch);+ break;+ }+ Ok(ch) => {+ if asked_repo.is_some() {+ asked_check = Some(ch);+ }+ }+ // GitHub didn't answer (a rate limit, an outage): kept for the poller to retry+ Err(_) => {+ unanswered.get_or_insert(c);+ }+ }+ }+ if let Some(found) = found {+ let full = found.repo.clone().unwrap_or_default();+ let same_repo = before.as_ref().is_some_and(|r| r.repo.eq_ignore_ascii_case(&full));+ let branch = match asked_branch {+ Some(b) => b.to_string(),+ None if same_repo && !before.as_ref().unwrap().branch.is_empty() => before.as_ref().unwrap().branch.clone(),+ None => found.branch.clone().unwrap_or_else(|| "main".into()),+ };+ if Some(&branch) != found.branch.as_ref() {+ match repo::client_for(&state, &full).await {+ Ok((c, _)) => match c.dev_branch_exists(&full, &branch).await {+ Ok(true) => {}+ Ok(false) => return error(StatusCode::BAD_REQUEST, format!("{full} has no branch {branch}")),+ Err(e) => return error(StatusCode::BAD_GATEWAY, e.to_string()),+ },Err(e) => return error(StatusCode::BAD_GATEWAY, e.to_string()),- },- Err(e) => return error(StatusCode::BAD_GATEWAY, e.to_string()),+ }}+ (full, branch, found.deploy_hint.map(str::to_string))+ } else if let Some(b) = kept_on {+ // A watched repo stays watched through a failed read; the poller says why+ (b.repo.clone(), asked_branch.map(str::to_string).unwrap_or_else(|| b.branch.clone()), b.deploy_hint.clone())+ } else if let Some((_, name)) = unanswered.as_deref().and_then(repo::normalize) {+ let source_branch = sources.iter().find(|s| s.repo.eq_ignore_ascii_case(&name)).and_then(|s| s.branch.clone());+ let branch = asked_branch.map(str::to_string).or(source_branch).unwrap_or_else(|| "main".into());+ (name, branch, None)+ } else {+ // On with no repo: the floor and guards work, the poller idles. The branch, when a+ // team folder says it, still tells the floor which branch is the main one.+ let branch = asked_branch.map(str::to_string).or_else(|| sources.iter().find_map(|s| s.branch.clone())).unwrap_or_default();+ (String::new(), branch, None)}- (full, branch, found.deploy_hint.map(str::to_string))} else {// Off: settings are kept as given, nothing is fetched (D12)let repo_name = match asked_repo {@@ -232,7 +392,13 @@ pub async fn put_mode(State(state): State<AppState>, headers: HeaderMap, Path(id}}let calls = state.db.dev_calls_today(space.as_str()).await.unwrap_or(0);- Json(row_json(&row, calls)).into_response()+ let mut v = row_json(&row, calls);+ with_sources(&state, Some(&row), sources, &hosts, &mut v).await;+ if let Some(c) = asked_check {+ // The repo asked for wasn't read: Dev mode is on without it, and this says why+ v["check"] = json!(c);+ }+ Json(v).into_response()}// ---------------------------------------------------------------------------------------------diff --git a/src/server/mod.rs b/src/server/mod.rsindex d05ce0a3..6cd2ba7c 100644--- a/src/server/mod.rs+++ b/src/server/mod.rs@@ -253,6 +253,7 @@ pub fn create_router(state: AppState) -> Router {.route("/api/spaces/:id/approvals", get(approval_modes::get_space).put(approval_modes::put_space)).route("/api/spaces/:id/dev_mode", get(dev::routes::get_mode).put(dev::routes::put_mode)).route("/api/spaces/:id/dev_mode/check", post(dev::routes::check))+ .route("/api/spaces/:id/dev_mode/seen", post(dev::routes::seen)).route("/api/spaces/:id/dev/landed", get(dev::routes::landed)).route("/api/spaces/:id/dev/landed/seen", post(dev::routes::seen)).route("/api/spaces/:id/dev/reviews", get(dev::routes::reviews))diff --git a/src/server/zombie_routes.rs b/src/server/zombie_routes.rsindex 442af8ce..ee76b6fb 100644--- a/src/server/zombie_routes.rs+++ b/src/server/zombie_routes.rs@@ -467,6 +467,10 @@ pub async fn add_source(State(state): State<AppState>, headers: HeaderMap, Json(let _ = hunt::forget_secret(state.credentials.as_ref(), &id).await;return Err(db_error(e));}+ if row.kind == "github" {+ // A space on with no repo watches the repo this connection now reads (Dev mode, QA B1)+ super::dev::routes::bind_detected_all(&state).await;+ }Ok((StatusCode::CREATED, Json(json!({"source": source_view(row), "test": test}))).into_response())}@@ -516,6 +520,9 @@ pub async fn update_source(State(state): State<AppState>, headers: HeaderMap, Parow.config = config;}state.db.zombie_put_source(&row).await.map_err(db_error)?;+ if row.kind == "github" && row.enabled {+ super::dev::routes::bind_detected_all(&state).await;+ }Ok(Json(json!({"source": source_view(row), "test": test})).into_response())}diff --git a/tests/dev_autodetect_test.rs b/tests/dev_autodetect_test.rsnew file mode 100644index 00000000..30d9a748--- /dev/null+++ b/tests/dev_autodetect_test.rs@@ -0,0 +1,444 @@+//! Dev mode on the existing setup (plan dev-mode/plan/any-git.md S1–S4): the switch finds the repo+//! in a team's folder with no question asked, turns on without a GitHub connection or any repo,+//! and no token in a folder's git remote reaches a reply, the database or a log line.+//!+//! The team folders are throwaway `git init` checkouts; GitHub is the shared mock on loopback.+//! Nothing here touches the network.++mod common;+#[path = "support/mock_github.rs"]+mod mock_github;++use common::*;+use kwnt::db::models::{NewKwant, NewTeam};+use kwnt::db::dev_mode::{LANDED, READY, REVIEW};+use kwnt::db::spaces::{NewSpace, SpaceId};+use kwnt::server::dev::poller;+use mock_github::*;+use serde_json::{json, Value};+use std::path::{Path, PathBuf};+use std::sync::{Arc, Mutex, OnceLock};++const PORTS: [u16; 2] = [9495, 9496];+const REPO: &str = "demo-org/demo-app";++static LOG: OnceLock<Arc<Mutex<Vec<u8>>>> = OnceLock::new();++struct Capture(Arc<Mutex<Vec<u8>>>);++impl std::io::Write for Capture {+ fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {+ self.0.lock().unwrap().extend_from_slice(b);+ Ok(b.len())+ }+ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+}++/// Every log line of this test binary, at debug (trace for kwnt itself).+fn capture_logs() -> Arc<Mutex<Vec<u8>>> {+ LOG.get_or_init(|| {+ let buf = Arc::new(Mutex::new(Vec::new()));+ let writer = buf.clone();+ let sub = tracing_subscriber::fmt()+ .with_env_filter(tracing_subscriber::EnvFilter::new("debug,kwnt=trace"))+ .with_ansi(false)+ .with_writer(move || Capture(writer.clone()))+ .finish();+ tracing::subscriber::set_global_default(sub).expect("no other subscriber in this binary");+ buf+ })+ .clone()+}++fn git(dir: &Path, args: &[&str]) {+ let out = std::process::Command::new("git").arg("-C").arg(dir).args(args).env("GIT_TERMINAL_PROMPT", "0").output().unwrap();+ assert!(out.status.success(), "git {args:?}: {}", String::from_utf8_lossy(&out.stderr));+}++/// A checkout at `dir` on `main` with `origin` at `url` (when given).+fn checkout(dir: &Path, url: Option<&str>) -> PathBuf {+ std::fs::create_dir_all(dir).unwrap();+ git(dir, &["init", "-q", "-b", "main"]);+ if let Some(u) = url {+ git(dir, &["remote", "add", "origin", u]);+ }+ dir.to_path_buf()+}++async fn team(env: &Env, name: &str, folder: Option<&Path>) {+ team_in(env, &SpaceId::default_space(), name, folder).await+}++async fn team_in(env: &Env, space: &SpaceId, name: &str, folder: Option<&Path>) {+ let lead = if space.is_default() {+ env.a.clone()+ } else {+ let k = NewKwant {+ name: format!("{name} lead"),+ title: "Lead".into(),+ persona_prompt: "Test persona".into(),+ soul: String::new(),+ avatar_sprite: "s".into(),+ driver_type: "api".into(),+ preferred_model: "claude".into(),+ };+ env.state.db.create_kwant(space, &k).await.unwrap().id+ };+ let t = NewTeam {+ name: name.into(),+ description: None,+ icon: None,+ lead_kwant_id: lead.clone(),+ member_kwants: vec![lead],+ workspace_path: folder.map(|f| f.to_string_lossy().to_string()),+ repo_url: None,+ };+ env.state.db.create_team(space, &t).await.unwrap();+}++fn uri() -> String {+ uri_of(&SpaceId::default_space())+}++fn uri_of(space: &SpaceId) -> String {+ format!("/api/spaces/{}/dev_mode", space.as_str())+}++/// Every file under `dir` that holds `needle`.+fn files_with(dir: &Path, needle: &[u8], out: &mut Vec<String>) {+ for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {+ let p = entry.path();+ if p.is_dir() {+ files_with(&p, needle, out);+ } else if std::fs::read(&p).is_ok_and(|b| b.windows(needle.len()).any(|w| w == needle)) {+ out.push(p.display().to_string());+ }+ }+}++#[tokio::test]+async fn an_empty_space_turns_on_with_no_repo_and_the_poller_idles() {+ let env = setup().await;+ let (s, v) = call(&env.app, "GET", &uri(), None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!((v["status"].as_str(), v["sources"].clone(), v["repo"].clone()), (Some("no_repo"), json!([]), Value::Null), "{v}");++ let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true}))).await;+ assert_eq!(s.as_u16(), 200, "on with no repo is not a 409: {v}");+ assert_eq!(v["on"], true);+ assert_eq!(v["repo"], Value::Null);+ assert_eq!(v["status"], "no_repo");+ assert!(v.get("check").is_none(), "nothing was asked for: {v}");+ // The floor turns on with the switch, repo or not+ assert!(env.state.db.any_dev_mode_on());+ let mode = env.state.db.dev_mode(SpaceId::default_space().as_str()).await.unwrap().unwrap();+ assert!(mode.on && mode.repo.is_empty());+ // The poller idles: no read, no error+ poller::poll(&env.state, &mode).await.expect("an empty repo polls clean");+ poller::poll_logged(&env.state, mode).await;+ let after = env.state.db.dev_mode(SpaceId::default_space().as_str()).await.unwrap().unwrap();+ assert_eq!(after.poll_error, None);++ // Off and on again keeps working+ let (s, _) = call(&env.app, "PUT", &uri(), Some(json!({"on": false}))).await;+ assert_eq!(s.as_u16(), 200);+ let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true, "backup_command": "pg_dump demo > /tmp/demo.sql"}))).await;+ assert_eq!((s.as_u16(), v["on"].clone(), v["backup_command"].clone()), (200, json!(true), json!("pg_dump demo > /tmp/demo.sql")), "{v}");+}++#[tokio::test]+async fn with_no_connection_it_still_turns_on_and_no_token_leaks() {+ let logs = capture_logs();+ let env = setup().await;+ let token = canary_token();+ let folders = env.tmp.path().join("folders");+ let web = checkout(&folders.join("web"), Some(&format!("https://x-access-token:{token}@github.com/{REPO}.git")));+ let ops = checkout(&folders.join("ops"), Some(&format!("https://deploy:{token}@gitlab.example.com/group/sub/ops.git")));+ git(&ops, &["symbolic-ref", "refs/remotes/origin/HEAD", "refs/remotes/origin/trunk"]);+ team(&env, "Web", Some(&web)).await;+ team(&env, "Ops", Some(&ops)).await;+ let mut replies = Vec::new();++ let (s, v) = call(&env.app, "GET", &uri(), None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["status"], "not_connected", "{v}");+ assert_eq!(v["repo"], REPO, "the folder's repo is the prefill");+ assert_eq!(+ v["sources"],+ json!([+ {"team": "Web", "repo": REPO, "host": "github.com", "from": "folder"},+ {"team": "Ops", "repo": "group/sub/ops", "host": "gitlab.example.com", "from": "folder"},+ ])+ );+ replies.push(v);++ let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true}))).await;+ assert_eq!(s.as_u16(), 200, "no connection is not a 409: {v}");+ assert_eq!((v["on"].clone(), v["repo"].clone(), v["status"].clone()), (json!(true), Value::Null, json!("not_connected")), "{v}");+ assert_eq!(v["branch"], "main", "the floor still learns the folder's branch");+ replies.push(v);++ // A repo asked for by name that nothing reads: on anyway, with the check saying why+ let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true, "repo": format!("https://u:{token}@github.com/{REPO}")}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!((v["on"].clone(), v["repo"].clone(), v["check"]["state"].clone(), v["check"]["repo"].clone()), (json!(true), Value::Null, json!("not_connected"), json!(REPO)), "the token is dropped and the repo still read: {v}");+ replies.push(v);+ // ...and one with no connection problem but no such repo name says not_found (Pixel's two reasons)+ let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true, "repo": "not a repo"}))).await;+ assert_eq!((s.as_u16(), v["on"].clone(), v["repo"].clone(), v["check"]["state"].clone()), (200, json!(true), Value::Null, json!("not_found")), "{v}");+ replies.push(v);+ let (_, v) = call(&env.app, "POST", &format!("{}/check", uri()), Some(json!({}))).await;+ assert_eq!((v["state"].clone(), v["repo"].clone()), (json!("not_connected"), json!(REPO)), "the check reads the folder's repo: {v}");+ replies.push(v);++ // A space whose only remotes are on other hosts says so+ let teams = env.state.db.list_teams(&SpaceId::default_space()).await.unwrap();+ env.state.db.delete_team(&teams.iter().find(|t| t.name == "Web").unwrap().id).await.unwrap();+ let (_, v) = call(&env.app, "GET", &uri(), None).await;+ assert_eq!((v["status"].clone(), v["sources"][0]["host"].clone()), (json!("other_host"), json!("gitlab.example.com")), "{v}");+ replies.push(v);++ let folder = folders.to_string_lossy().to_string();+ for r in &replies {+ let text = r.to_string();+ assert!(!text.contains(&token), "the token reached a reply: {text}");+ assert!(!text.contains(&folder), "a folder path reached a reply: {text}");+ }+ let log = String::from_utf8_lossy(&logs.lock().unwrap()).to_string();+ assert!(!log.contains(&token), "the token reached a log line");+ let mut leaked = Vec::new();+ files_with(&env.tmp.path().join("data"), token.as_bytes(), &mut leaked);+ assert!(leaked.is_empty(), "the token was stored in {leaked:?}");+}++#[tokio::test]+async fn a_github_checkout_is_watched_with_no_repo_given() {+ let _logs = capture_logs();+ let env = setup().await;+ env.state.db.set_space_approvals(&SpaceId::default_space(), "ask").await.unwrap();+ let token = canary_token();+ let gh = MockGithub::start(&PORTS).await;+ gh.require_token(&token);+ let r = format!("/repos/{REPO}");+ gh.json("/user", user("demo-person"))+ .json(&r, repo(REPO, "main"))+ .json(&format!("{r}/contents"), json!([{"name": "fly.toml", "type": "file"}]));+ let (s, v) = call(&env.app, "POST", "/api/zombie/sources", Some(json!({"kind": "github", "label": "GitHub", "config": {"api_base": gh.base}, "secret": token}))).await;+ assert_eq!(s.as_u16(), 201, "{v}");++ // The team's folder is a checkout of the repo on the connection's host, its URL holding a+ // token of its own; a second team with no git folder comes first+ let folder_token = canary_token();+ let host = gh.base.trim_start_matches("http://");+ let web = checkout(&env.tmp.path().join("folders/web"), Some(&format!("http://bot:{folder_token}@{host}/{REPO}.git")));+ let empty = env.tmp.path().join("folders/plain");+ std::fs::create_dir_all(&empty).unwrap();+ team(&env, "Plain", Some(&empty)).await;+ team(&env, "Web", Some(&web)).await;++ let (_, v) = call(&env.app, "GET", &uri(), None).await;+ assert_eq!((v["on"].clone(), v["status"].clone(), v["repo"].clone()), (json!(false), json!("watching"), json!(REPO)), "off, it says what on would watch: {v}");+ let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert_eq!(v["repo"], REPO, "{v}");+ assert_eq!(v["branch"], "main");+ assert_eq!(v["deploy_hint"], "fly");+ assert_eq!(v["status"], "watching");+ assert_eq!(v["sources"], json!([{"team": "Web", "repo": REPO, "host": "127.0.0.1", "from": "folder"}]));+ let (_, got) = call(&env.app, "GET", &uri(), None).await;+ assert_eq!((got["status"].clone(), got["repo"].clone()), (json!("watching"), json!(REPO)));+ for text in [v.to_string(), got.to_string()] {+ assert!(!text.contains(&folder_token) && !text.contains(&token), "a token reached a reply: {text}");+ }++ // A watched repo stays watched when GitHub stops answering+ gh.fault(&r, Fault::Server(502));+ let (s, v) = call(&env.app, "PUT", &uri(), Some(json!({"on": true}))).await;+ assert_eq!((s.as_u16(), v["repo"].clone(), v["branch"].clone()), (200, json!(REPO), json!("main")), "{v}");+ gh.heal(&r);+ gh.assert_read_only();+}++fn sha(n: u8) -> String {+ format!("{n:0>40}")+}++/// Two commits on main (one through a merged PR) and one open PR, as the poller reads them.+fn seed(gh: &MockGithub, r: &str) {+ let person = ("Lin (kwant bot)", "[email protected]");+ let with_files = |mut c: Value, files: Value| {+ c["files"] = files;+ c+ };+ let patch = "@@ -1,2 +1,2 @@\n-let retries = 1;\n+let retries = 3;";+ let merged = commit(&sha(2), "Retry the upload (#5)", person, &[&sha(1)], "2026-11-05T02:00:00Z");+ let direct = commit(&sha(1), "Fix the README", person, &[], "2026-11-05T01:00:00Z");+ gh.json(&format!("{r}/branches/main"), json!({"name": "main"}))+ .json(&format!("{r}/tags"), json!([]))+ .json(&format!("{r}/commits"), json!([merged, direct]))+ .json(&format!("{r}/commits/{}", sha(2)), with_files(merged.clone(), json!([file("src/upload.rs", "modified", patch)])))+ .json(&format!("{r}/commits/{}", sha(1)), with_files(direct.clone(), json!([file("README.md", "modified", "-old\n+new")])))+ .json(&format!("{r}/commits/{}/pulls", sha(2)), json!([pull(5, "Retry the upload", ("retry", &sha(9)), "main", "demo-person", Some((&sha(2), "2026-11-05T02:00:00Z")))]))+ .json(&format!("{r}/commits/{}/pulls", sha(1)), json!([]))+ .json(&format!("{r}/pulls/5/files"), json!([file("src/upload.rs", "modified", patch)]))+ .json(&format!("{r}/commits/{}/check-runs", sha(2)), check_runs(&[("rust", "completed", Some("success"))]))+ .json(&format!("{r}/commits/{}/check-runs", sha(1)), check_runs(&[("rust", "completed", Some("success"))]))+ .json(&format!("{r}/pulls"), json!([pull(8, "Add a cache", ("cache", &sha(3)), "main", "demo-person", None)]))+ .json(&format!("{r}/pulls/8/files"), json!([file("src/cache.rs", "added", "+pub struct Cache;")]))+ .json(&format!("{r}/commits/{}", sha(3)), commit(&sha(3), "Add a cache", person, &[&sha(2)], "2026-11-05T03:00:00Z"))+ .json(&format!("{r}/commits/{}/check-runs", sha(3)), check_runs(&[("rust", "completed", Some("success"))]));+}++/// Plan user-flow.md F4, F6 and F10, in a space of its own so the poller's wake list is this+/// test's alone.+#[tokio::test]+async fn a_detected_repo_wakes_the_poller_counts_new_reviews_and_never_replaces_a_typed_one() {+ let env = setup().await;+ let space = env.state.db.create_space(&NewSpace { name: "Shop".into(), icon: "S".into(), color: None, this_machine_enabled: true }).await.unwrap();+ let space = SpaceId::new(space.id);+ // An asking install (every space), so the login may be saved here+ for s in [&space, &SpaceId::default_space()] {+ env.state.db.set_space_approvals(s, "ask").await.unwrap();+ }+ let token = canary_token();+ let gh = MockGithub::start(&PORTS).await;+ gh.require_token(&token);+ let r = format!("/repos/{REPO}");+ gh.json("/user", user("demo-person")).json(&r, repo(REPO, "main")).json(&format!("{r}/contents"), json!([{"name": "Cargo.toml", "type": "file"}]));+ seed(&gh, &r);+ let other = "demo-org/typed-app";+ gh.json(&format!("/repos/{other}"), repo(other, "main")).json(&format!("/repos/{other}/contents"), json!([]));+ let (s, v) = call(&env.app, "POST", "/api/zombie/sources", Some(json!({"kind": "github", "label": "GitHub", "config": {"api_base": gh.base}, "secret": token}))).await;+ assert_eq!(s.as_u16(), 201, "{v}");+ let host = gh.base.trim_start_matches("http://").split(':').next().unwrap();+ let web = checkout(&env.tmp.path().join("folders/shop"), Some(&format!("{}/{REPO}.git", gh.base)));+ team_in(&env, &space, "Shop", Some(&web)).await;+ let u = uri_of(&space);++ // F4: switching on with the repo found in the folder wakes the poller for this space at once+ assert!(!poller::is_due_soon(space.as_str()));+ let (s, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;+ assert_eq!((s.as_u16(), v["repo"].clone(), v["status"].clone()), (200, json!(REPO), json!("watching")), "{v}");+ assert_eq!(v["sources"], json!([{"team": "Shop", "repo": REPO, "host": host, "from": "folder"}]));+ assert!(poller::is_due_soon(space.as_str()), "on with a detected repo wakes the poller");+ // ...and that first poll backfills (both commits are within BACKFILL) plus the open PR+ let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();+ poller::poll(&env.state, &mode).await.expect("a clean first poll");+ let landed = env.state.db.dev_cards(space.as_str(), LANDED, None, 50).await.unwrap();+ let reviews = env.state.db.dev_cards(space.as_str(), REVIEW, None, 50).await.unwrap();+ assert_eq!((landed.len(), reviews.len()), (2, 1), "the first poll backfilled");+ assert!(landed.len() <= poller::BACKFILL);++ // F6: never seen counts nothing, so an update shows no surprise badge+ let (_, v) = call(&env.app, "GET", &u, None).await;+ assert_eq!(v["new_reviews"], 0, "{v}");+ let (s, v) = call(&env.app, "POST", &format!("{u}/seen"), None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ assert!(v["seen_at"].is_string(), "{v}");+ tokio::time::sleep(std::time::Duration::from_millis(20)).await;+ let fresh_review = env.state.db.insert_dev_card(space.as_str(), REVIEW, "pr:41", &sha(41), "{}").await.unwrap().unwrap();+ env.state.db.set_dev_card(&fresh_review.id, READY, Some(&json!({"headline": "Review"}).to_string())).await.unwrap();+ let fresh_landed = env.state.db.insert_dev_card(space.as_str(), LANDED, &sha(42), &sha(42), "{}").await.unwrap().unwrap();+ env.state.db.set_dev_card(&fresh_landed.id, READY, Some(&json!({"headline": "Landed"}).to_string())).await.unwrap();+ let (_, v) = call(&env.app, "GET", &u, None).await;+ assert_eq!(v["new_reviews"], 1, "one review since seen; the landed card doesn't count: {v}");+ let (_, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;+ assert_eq!(v["new_reviews"], 1, "the PUT reply carries it too: {v}");+ let (s, _) = call(&env.app, "POST", &format!("{u}/seen"), None).await;+ assert_eq!(s.as_u16(), 200);+ let (_, v) = call(&env.app, "GET", &u, None).await;+ assert_eq!(v["new_reviews"], 0, "seen clears the count: {v}");++ // F10: a repo the person typed is kept; the folder's repo never replaces it+ let (s, v) = call(&env.app, "PUT", &u, Some(json!({"on": true, "repo": other}))).await;+ assert_eq!((s.as_u16(), v["repo"].clone()), (200, json!(other)), "{v}");+ let (_, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;+ assert_eq!((v["repo"].clone(), v["status"].clone()), (json!(other), json!("watching")), "{v}");+ let (_, v) = call(&env.app, "PUT", &u, Some(json!({"on": false}))).await;+ assert_eq!(v["on"], false);+ let (_, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;+ assert_eq!(v["repo"], json!(other), "off and on again keeps the typed repo: {v}");+ let (_, v) = call(&env.app, "GET", &u, None).await;+ assert_eq!((v["repo"].clone(), v["status"].clone()), (json!(other), json!("watching")), "{v}");+ gh.assert_read_only();+}++/// QA B1: on with a detected repo and no connection, then the person connects GitHub. The repo is+/// bound and the poller wakes with no off and on; a space that is off is left alone.+#[tokio::test]+async fn connecting_github_while_on_binds_the_detected_repo_without_off_and_on() {+ let env = setup().await;+ let mk = |name: &str| NewSpace { name: name.into(), icon: "S".into(), color: None, this_machine_enabled: true };+ let space = SpaceId::new(env.state.db.create_space(&mk("Shop")).await.unwrap().id);+ let off = SpaceId::new(env.state.db.create_space(&mk("Idle")).await.unwrap().id);+ for s in [&space, &off, &SpaceId::default_space()] {+ env.state.db.set_space_approvals(s, "ask").await.unwrap();+ }+ let token = canary_token();+ let gh = MockGithub::start(&PORTS).await;+ gh.require_token(&token);+ let r = format!("/repos/{REPO}");+ gh.json("/user", user("demo-person")).json(&r, repo(REPO, "main")).json(&format!("{r}/contents"), json!([{"name": "fly.toml", "type": "file"}]));+ seed(&gh, &r);+ let web = checkout(&env.tmp.path().join("folders/shop"), Some(&format!("{}/{REPO}.git", gh.base)));+ team_in(&env, &space, "Shop", Some(&web)).await;+ team_in(&env, &off, "Idle", Some(&web)).await;++ // On before any connection: no repo. (The mock's host only counts as GitHub once a connection+ // names it, so here it reads other_host; on github.com it is not_connected.)+ let u = uri_of(&space);+ let (s, v) = call(&env.app, "PUT", &u, Some(json!({"on": true}))).await;+ assert_eq!((s.as_u16(), v["on"].clone(), v["repo"].clone()), (200, json!(true), Value::Null), "{v}");+ let (_, v) = call(&env.app, "GET", &u, None).await;+ assert_eq!(v["repo"], Value::Null, "no connection yet: {v}");+ // The wake from turning on has been taken by a poll, which had nothing to read+ let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();+ poller::poll(&env.state, &mode).await.unwrap();+ poller::take_due_soon(space.as_str());+ assert!(!poller::is_due_soon(space.as_str()));++ // The person connects GitHub (Loose ends) and comes back: no off, no on, no typing+ let (s, v) = call(&env.app, "POST", "/api/zombie/sources", Some(json!({"kind": "github", "label": "GitHub", "config": {"api_base": gh.base}, "secret": token}))).await;+ assert_eq!(s.as_u16(), 201, "{v}");+ assert!(!v.to_string().contains(&token));+ assert!(poller::is_due_soon(space.as_str()), "binding wakes the poller");+ let (_, v) = call(&env.app, "GET", &u, None).await;+ assert_eq!((v["on"].clone(), v["repo"].clone(), v["branch"].clone(), v["status"].clone()), (json!(true), json!(REPO), json!("main"), json!("watching")), "{v}");+ assert_eq!(v["deploy_hint"], "fly");+ let mode = env.state.db.dev_mode(space.as_str()).await.unwrap().unwrap();+ poller::poll(&env.state, &mode).await.expect("the bound repo polls");+ assert_eq!(env.state.db.dev_cards(space.as_str(), LANDED, None, 50).await.unwrap().len(), 2, "the first poll backfilled");++ // A space that is off stays off with no repo; its GET only says what on would watch+ assert!(env.state.db.dev_mode(off.as_str()).await.unwrap().is_none());+ let (_, v) = call(&env.app, "GET", &uri_of(&off), None).await;+ assert_eq!((v["on"].clone(), v["status"].clone()), (json!(false), json!("watching")), "{v}");+ assert!(env.state.db.dev_mode(off.as_str()).await.unwrap().is_none(), "a GET never writes an off space");++ // A changed GitHub source binds every space that is on with no repo, with no GET needed+ let changed = SpaceId::new(env.state.db.create_space(&mk("Changed")).await.unwrap().id);+ let read = SpaceId::new(env.state.db.create_space(&mk("Read")).await.unwrap().id);+ for s in [&changed, &read] {+ team_in(&env, s, "Web", Some(&web)).await;+ env.state.db.put_dev_mode(s.as_str(), true, "", "", None, None).await.unwrap();+ }+ let (s, v) = call(&env.app, "GET", "/api/zombie/sources", None).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ let id = v["sources"].as_array().unwrap().iter().find(|x| x["kind"] == "github").unwrap()["id"].as_str().unwrap().to_string();+ let (s, v) = call(&env.app, "PATCH", &format!("/api/zombie/sources/{id}"), Some(json!({"label": "GitHub (work)"}))).await;+ assert_eq!(s.as_u16(), 200, "{v}");+ for s in [&changed, &read] {+ let m = env.state.db.dev_mode(s.as_str()).await.unwrap().unwrap();+ assert_eq!((m.on, m.repo.as_str(), m.branch.as_str()), (true, REPO, "main"), "the source change bound {}", s.as_str());+ }+ // When no source change happened, the GET falls back to the same binding+ let late = SpaceId::new(env.state.db.create_space(&mk("Late")).await.unwrap().id);+ team_in(&env, &late, "Web", Some(&web)).await;+ env.state.db.put_dev_mode(late.as_str(), true, "", "", None, None).await.unwrap();+ let (_, v) = call(&env.app, "GET", &uri_of(&late), None).await;+ assert_eq!((v["repo"].clone(), v["status"].clone()), (json!(REPO), json!("watching")), "the GET fallback bound it: {v}");+ assert!(poller::is_due_soon(late.as_str()));+ gh.assert_read_only();+}