Skip to content

armgit / kwant

Public Imported from GitHub
0

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.

0.7.2: Dev mode repo fixes from QA (h, c, g) (#362)

Oleksandr Ivanchenko0bceab452485
diff --git a/src/db/dev_mode.rs b/src/db/dev_mode.rs
index d26ee3bc..556ab019 100644
--- a/src/db/dev_mode.rs
+++ b/src/db/dev_mode.rs
@@ -498,6 +498,13 @@ impl Database {
Ok(done.rows_affected() == 1)
}
+ /// Records why a row can't be read without marking it polled (a row added while off whose
+ /// repo the switch-on check didn't find).
+ pub async fn set_dev_repo_error(&self, space_id: &str, key: &str, error: &str) -> Result<bool, DbError> {
+ let done = sqlx::query("UPDATE dev_repos SET poll_error = ?3 WHERE space_id = ?1 AND key = ?2").bind(space_id).bind(key).bind(error).execute(&self.pool).await?;
+ Ok(done.rows_affected() == 1)
+ }
+
/// Sets a row's deploy hint (from its root files, when GitHub was read).
pub async fn set_dev_repo_hint(&self, space_id: &str, key: &str, hint: Option<&str>) -> Result<(), DbError> {
sqlx::query("UPDATE dev_repos SET deploy_hint = ?3 WHERE space_id = ?1 AND key = ?2").bind(space_id).bind(key).bind(hint).execute(&self.pool).await?;
diff --git a/src/server/dev/repo.rs b/src/server/dev/repo.rs
index 34e45661..6ee0e5d4 100644
--- a/src/server/dev/repo.rs
+++ b/src/server/dev/repo.rs
@@ -124,9 +124,11 @@ pub async fn clients(state: &AppState) -> Result<Vec<(GithubConfig, GithubSource
}
}
-/// The client whose connection can read `repo` (the first that finds it), with the repo.
+/// The client whose connection can read `repo` (the first that finds it), with the repo. With no
+/// connection the error says so (why [`clients`] found none), never a refused token: the desk
+/// shows such a row as `not_connected` (QA h).
pub async fn client_for(state: &AppState, repo: &str) -> Result<(GithubSource, crate::zombie::github::GhRepo), GhError> {
- let list = clients(state).await.map_err(|_| GhError::Auth)?;
+ let list = clients(state).await.map_err(GhError::Other)?;
let mut last = GhError::NotFound;
for (_, c) in list {
match c.dev_repo(repo).await {
@@ -548,14 +550,23 @@ pub async fn reconcile(state: &AppState, space: &SpaceId) -> Reconciled {
}
let mut rows = db.dev_repos(sp).await.unwrap_or_default();
- // Rows added while off have no branch yet
+ // Rows added while off have no branch yet. One the check can't read keeps no branch (the
+ // poller skips it) and records why, so the desk shows an error, not watching (QA g); the next
+ // reconcile checks again, and setting the branch clears the error.
for r in rows.iter().filter(|r| r.branch.trim().is_empty()) {
- if let Ok(found) = check(state, space, &r.check_input()).await {
- if found.state == "found" {
+ let why = match check(state, space, &r.check_input()).await {
+ Ok(found) if found.state == "found" => {
let branch = found.branch.clone().unwrap_or_else(|| "main".into());
let _ = db.set_dev_repo_branch(sp, &r.key, &branch).await;
let _ = db.set_dev_repo_hint(sp, &r.key, found.deploy_hint).await;
+ continue;
}
+ Ok(found) if found.state == "not_connected" => clients(state).await.err().unwrap_or_else(|| GhError::Auth.to_string()),
+ Ok(_) => GhError::NotFound.to_string(),
+ Err(e) => e,
+ };
+ if r.poll_error.as_deref() != Some(why.as_str()) {
+ let _ = db.set_dev_repo_error(sp, &r.key, &why).await;
}
}
diff --git a/src/server/dev/routes.rs b/src/server/dev/routes.rs
index e86aaa15..8854ae8d 100644
--- a/src/server/dev/routes.rs
+++ b/src/server/dev/routes.rs
@@ -100,9 +100,13 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
// Only while off does a source with no row hang on a connection existing
let ask = !on && list.iter().any(|e| e.row.is_none() && e.source.is_some_and(|s| s.on_github(&hosts)));
let connected = ask && repo::clients(state).await.is_ok();
+ // A row whose poll failed because no connection reads GitHub any more (deleted, or the vault
+ // locked) needs the connection, not a retry: it reads not_connected (QA h)
+ let lost = rows.iter().any(|r| r.poll_error.is_some()) && repo::clients(state).await.is_err();
let mut repos = Vec::new();
for e in &list {
let status = match (e.row, e.source) {
+ (Some(r), _) if r.poll_error.is_some() && lost => "not_connected",
(Some(r), _) if r.poll_error.is_some() => "error",
(Some(_), _) => "watching",
(None, Some(s)) if !s.on_github(&hosts) => "other_host",
@@ -157,7 +161,14 @@ pub async fn mode_json(state: &AppState, space: &SpaceId) -> Result<Value, Respo
"calls_cap": super::call_cap(),
});
let any_watching = repos.iter().any(|r| matches!(r["status"].as_str(), Some("watching" | "error")));
- v["status"] = json!(if any_watching { "watching" } else { repo::status(on, "", &sources, &hosts, connected) });
+ let any_unread = repos.iter().any(|r| r["status"] == "not_connected");
+ v["status"] = json!(if any_watching {
+ "watching"
+ } else if any_unread {
+ "not_connected"
+ } else {
+ repo::status(on, "", &sources, &hosts, connected)
+ });
v["sources"] = json!(sources);
v["new_reviews"] = json!(new_reviews(state, row.as_ref()).await);
// Where a review would be posted, and as whom (post-to-github.md P7 and its amendment)
@@ -504,6 +515,8 @@ pub async fn delete_repo(State(state): State<AppState>, headers: HeaderMap, Path
Ok(_) => tracing::info!(space = %space, repo = %row.repo, "the person stopped watching a repo"),
Err(e) => return internal(e),
}
+ // The freed place goes to a team repo left out at the cap now, not at the next read (QA c)
+ repo::reconcile(&state, &space).await;
mode_reply(&state, &space).await
}
diff --git a/tests/dev_team_repos_test.rs b/tests/dev_team_repos_test.rs
index e79ec43f..3ba0e2a7 100644
--- a/tests/dev_team_repos_test.rs
+++ b/tests/dev_team_repos_test.rs
@@ -417,3 +417,124 @@ async fn the_routes_say_what_went_wrong() {
assert_eq!((s.as_u16(), v["code"].clone()), (400, json!("no_branch")), "{v}");
gh.assert_read_only();
}
+
+// ---- QA 0.7.2 (qa-072.md) h, c, g ------------------------------------------------------------
+
+/// QA h: a GitHub connection deleted after a poll leaves the rows reading `not_connected` (Needs
+/// GitHub, Connect), not an error about a refused token; connecting again recovers to watching.
+#[tokio::test]
+async fn a_lost_connection_reads_as_not_connected_and_reconnecting_recovers() {
+ let env = setup().await;
+ let gh = MockGithub::start(&[0]).await;
+ seed(&gh, APP);
+ seed(&gh, SITE);
+ let sp = space(&env, &gh, "Lost").await;
+ team(&env, &sp, "App", &gh, Some(APP)).await;
+ team(&env, &sp, "Site", &gh, Some(SITE)).await;
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ let (_, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "team"), row(SITE, "Site", "watching", "team")], "{v}");
+
+ // The connection goes; the next poll can't read either repo
+ let (_, list) = call(&env.app, "GET", "/api/zombie/sources", None).await;
+ let ids: Vec<String> = list["sources"].as_array().unwrap_or_else(|| panic!("{list}")).iter().filter(|s| s["kind"] == "github").map(|s| s["id"].as_str().unwrap().to_string()).collect();
+ assert_eq!(ids.len(), 1, "{list}");
+ let (s, v) = call(&env.app, "DELETE", &format!("/api/zombie/sources/{}", ids[0]), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ for r in env.state.db.dev_repos(sp.id.as_str()).await.unwrap() {
+ let e = r.poll_error.unwrap_or_else(|| panic!("{}: the failed poll is recorded", r.key));
+ assert!(!e.contains("401") && !e.contains("refused the token"), "no connection isn't a refused token: {e}");
+ }
+ let (_, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(rows(&v), vec![row(APP, "App", "not_connected", "team"), row(SITE, "Site", "not_connected", "team")], "{v}");
+ assert_eq!(v["status"], "not_connected", "{v}");
+
+ // Connecting again: watching after the next poll, errors cleared
+ let token = canary_token();
+ gh.require_token(&token);
+ 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}");
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ let (_, v) = call(&env.app, "GET", &uri(&sp), None).await;
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "team"), row(SITE, "Site", "watching", "team")], "{v}");
+ assert_eq!(v["status"], "watching", "{v}");
+ assert!(v["repos"].as_array().unwrap().iter().all(|r| r["poll_error"].is_null()), "{v}");
+ gh.assert_read_only();
+}
+
+/// QA c: at the cap, removing a hand row gives its place to the team repo that was left out right
+/// away, not at a read 30 s later.
+#[tokio::test]
+async fn removing_a_hand_repo_at_the_cap_watches_the_team_repo_left_out() {
+ let env = setup().await;
+ let gh = MockGithub::start(&[0]).await;
+ let sp = space(&env, &gh, "Cap").await;
+ let names: Vec<String> = (0..MAX_REPOS).map(|i| format!("demo-org/r{i:02}")).collect();
+ for n in &names {
+ seed(&gh, n);
+ }
+ seed(&gh, TOOLS);
+ // Nine teams with a repo, and a tenth with none yet
+ for (i, n) in names.iter().enumerate() {
+ team(&env, &sp, &format!("Team {i:02}"), &gh, (i + 1 < MAX_REPOS).then_some(n.as_str())).await;
+ }
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"repo": format!("{}/{TOOLS}", gh.base)}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(env.state.db.dev_repos(sp.id.as_str()).await.unwrap().len(), MAX_REPOS, "{v}");
+ // The tenth team links its repo: no place left
+ let last = &names[MAX_REPOS - 1];
+ let team10 = format!("Team {:02}", MAX_REPOS - 1);
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"repo": format!("{}/{last}", gh.base), "team": team10}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let got = rows(&v);
+ assert!(got.contains(&row(last, &team10, "too_many", "-")), "{v}");
+
+ // Removing the hand repo: the tenth team's repo is watched in the same reply
+ let tools_key = repo_key(&host(&gh), TOOLS);
+ let (s, v) = call(&env.app, "DELETE", &format!("{}/repos/{}", uri(&sp), enc(&tools_key)), None).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ let got = rows(&v);
+ assert_eq!(got.len(), MAX_REPOS, "{v}");
+ assert!(got.contains(&row(last, &team10, "watching", "team")), "{v}");
+ assert!(env.state.db.dev_repo(sp.id.as_str(), &repo_key(&host(&gh), last)).await.unwrap().is_some());
+ gh.assert_read_only();
+}
+
+/// QA g: a repo added while off that GitHub doesn't have reads as an error after switch-on, not
+/// watching with no branch; once it exists, the next reconcile reads its branch and clears it.
+#[tokio::test]
+async fn a_missing_repo_added_while_off_reads_as_an_error_at_switch_on() {
+ let env = setup().await;
+ let gh = MockGithub::start(&[0]).await;
+ seed(&gh, APP);
+ let sp = space(&env, &gh, "Ghost").await;
+ team(&env, &sp, "App", &gh, Some(APP)).await;
+ const GHOST: &str = "demo-org/ghost";
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"repo": format!("{}/{GHOST}", gh.base)}))).await;
+ assert_eq!(s.as_u16(), 200, "off keeps it as given: {v}");
+ let key = repo_key(&host(&gh), GHOST);
+ assert_eq!(env.state.db.dev_repo(sp.id.as_str(), &key).await.unwrap().map(|r| r.branch), Some(String::new()));
+
+ let (s, v) = call(&env.app, "PUT", &uri(&sp), Some(json!({"on": true}))).await;
+ assert_eq!(s.as_u16(), 200, "{v}");
+ assert_eq!(rows(&v), vec![row(APP, "App", "watching", "team"), row(GHOST, "-", "error", "hand")], "{v}");
+ let ghost = &v["repos"][1];
+ assert!(ghost["poll_error"].as_str().is_some_and(|e| e.contains("no such repo")), "{v}");
+ assert!(ghost["branch"].is_null(), "{v}");
+ assert_eq!(v["status"], "watching", "the other repo is still watched: {v}");
+ // A poll leaves the error (the row has no branch to read) and the other repo is read
+ poller::poll_space(&env.state, sp.id.as_str()).await;
+ assert!(env.state.db.dev_repo(sp.id.as_str(), &key).await.unwrap().unwrap().poll_error.is_some());
+
+ // It appears: the next reconcile fills its branch and clears the error
+ seed(&gh, GHOST);
+ repo::reconcile(&env.state, &sp.id).await;
+ let r = env.state.db.dev_repo(sp.id.as_str(), &key).await.unwrap().unwrap();
+ assert_eq!((r.branch.as_str(), r.poll_error.as_deref()), ("main", None));
+ gh.assert_read_only();
+}