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.

tests: relative fixture dates (dev_* expired on Nov 12) + the_65th + Telegram switch-off fix (src) (#529)

Oleksandr Ivanchenko0a86281e500e
diff --git a/src/db/telegram.rs b/src/db/telegram.rs
index f829be5f..cdfae3f8 100644
--- a/src/db/telegram.rs
+++ b/src/db/telegram.rs
@@ -382,32 +382,37 @@ impl Database {
/// The approvals switch. On needs a pairing; off always works.
pub async fn telegram_set_allow(&self, space: &str, on: bool) -> Result<bool, DbError> {
+ if !on {
+ return Ok(self.telegram_allow_off(space).await?.0);
+ }
let now = crate::clock::now();
- let r = if on {
- sqlx::query("UPDATE telegram_links SET allow_approvals = 1, allow_since = COALESCE(allow_since, ?), updated_at = ? WHERE space_id = ? AND state = ?")
- .bind(now)
- .bind(now)
- .bind(space)
- .bind(PAIRED)
- .execute(&self.pool)
- .await?
- } else {
- let r = sqlx::query("UPDATE telegram_links SET allow_approvals = 0, allow_since = NULL, updated_at = ? WHERE space_id = ?")
- .bind(now)
- .bind(space)
- .execute(&self.pool)
- .await?;
- self.telegram_disarm_asks(space).await?;
- r
- };
+ let r = sqlx::query("UPDATE telegram_links SET allow_approvals = 1, allow_since = COALESCE(allow_since, ?), updated_at = ? WHERE space_id = ? AND state = ?")
+ .bind(now)
+ .bind(now)
+ .bind(space)
+ .bind(PAIRED)
+ .execute(&self.pool)
+ .await?;
Ok(r.rows_affected() == 1)
}
+ /// The switch goes off. Also returns the asks this call disarmed, each with the Telegram
+ /// message id it had at that moment: the caller edits those that have one, and the sender
+ /// edits the others once their id is stored (see [`Self::telegram_ask_sent`]).
+ pub async fn telegram_allow_off(&self, space: &str) -> Result<(bool, Vec<TelegramAsk>), DbError> {
+ let r = sqlx::query("UPDATE telegram_links SET allow_approvals = 0, allow_since = NULL, updated_at = ? WHERE space_id = ?")
+ .bind(crate::clock::now())
+ .bind(space)
+ .execute(&self.pool)
+ .await?;
+ let disarmed = self.telegram_disarm_asks(space).await?;
+ Ok((r.rows_affected() == 1, disarmed))
+ }
+
/// Every Allow once button still out stops counting, in the database, whether or not kwant can
- /// reach Telegram to edit the messages (Lin's M1).
- pub async fn telegram_disarm_asks(&self, space: &str) -> Result<(), DbError> {
- sqlx::query("UPDATE telegram_asks SET allow = 0 WHERE space_id = ?").bind(space).execute(&self.pool).await?;
- Ok(())
+ /// reach Telegram to edit the messages (Lin's M1). Returns the asks it disarmed (allow 1 → 0).
+ pub async fn telegram_disarm_asks(&self, space: &str) -> Result<Vec<TelegramAsk>, DbError> {
+ Ok(sqlx::query_as::<_, TelegramAsk>("UPDATE telegram_asks SET allow = 0 WHERE space_id = ? AND allow = 1 RETURNING *").bind(space).fetch_all(&self.pool).await?)
}
pub async fn telegram_set_state(&self, space: &str, state: &str, error: Option<&str>) -> Result<(), DbError> {
@@ -533,9 +538,10 @@ impl Database {
Ok(())
}
- pub async fn telegram_ask_sent(&self, id: &str, message_id: i64) -> Result<(), DbError> {
- sqlx::query("UPDATE telegram_asks SET message_id = ? WHERE id = ?").bind(message_id).bind(id).execute(&self.pool).await?;
- Ok(())
+ /// Stores the Telegram id of a sent ask and returns the ask as it is now. One statement, so
+ /// it and [`Self::telegram_disarm_asks`] never both miss (or both see) a card in flight.
+ pub async fn telegram_ask_sent(&self, id: &str, message_id: i64) -> Result<Option<TelegramAsk>, DbError> {
+ Ok(sqlx::query_as::<_, TelegramAsk>("UPDATE telegram_asks SET message_id = ? WHERE id = ? RETURNING *").bind(message_id).bind(id).fetch_optional(&self.pool).await?)
}
/// Closes an open ask. True for the one caller that closed it (an answer counts once).
diff --git a/src/server/telegram/bridge.rs b/src/server/telegram/bridge.rs
index 261035c9..5b96d3a7 100644
--- a/src/server/telegram/bridge.rs
+++ b/src/server/telegram/bridge.rs
@@ -657,16 +657,35 @@ async fn approval_closed(state: &AppState, id: &str, line: &str) {
/// stops counting at once, in the database (`telegram_set_allow(false)` disarms them all). Their
/// messages are edited to link-only when kwant can reach Telegram; offline the edit is skipped, and
/// a tap is refused either way (Lin's M1).
+///
+/// A card still on its way to Telegram has no message id yet, so it can't be edited here: the
+/// sender edits it as soon as its id is stored ([`ask_sent`]).
pub async fn allow_off(state: &AppState, space: &str) {
- let armed = state.db.telegram_open_asks(space, "approval", true).await.unwrap_or_default();
- let _ = state.db.telegram_set_allow(space, false).await;
+ let disarmed = state.db.telegram_allow_off(space).await.map(|(_, d)| d).unwrap_or_default();
let Some(r) = runner(state, space) else { return };
- for ask in armed {
- let details = match state.db.get_approval(&ask.ref_id).await.ok().flatten() {
- Some(a) => serde_json::from_str(&a.parameters).unwrap_or(Value::Null),
- None => Value::Null,
- };
- link_only(state, &r, &ask, &details).await;
+ for ask in disarmed {
+ if ask.kind == "approval" && ask.state == "open" && ask.message_id.is_some() {
+ link_only(state, &r, &ask, &approval_details(state, &ask).await).await;
+ }
+ }
+}
+
+/// An ask has just been sent and its Telegram id stored (`ask` is the row after that). If it went
+/// out with Allow once but the switch went off while it was on its way, nothing could edit it then,
+/// so it becomes link-only now.
+pub async fn ask_sent(state: &AppState, r: &Runner, ask: &TelegramAsk, markup: Option<&Value>) {
+ let sent_armed = markup
+ .and_then(|m| m["inline_keyboard"].as_array())
+ .is_some_and(|rows| rows.iter().filter_map(Value::as_array).flatten().any(|b| b["callback_data"].as_str().is_some_and(|d| d.starts_with("a:"))));
+ if sent_armed && ask.kind == "approval" && ask.state == "open" && !ask.allow {
+ link_only(state, r, ask, &approval_details(state, ask).await).await;
+ }
+}
+
+async fn approval_details(state: &AppState, ask: &TelegramAsk) -> Value {
+ match state.db.get_approval(&ask.ref_id).await.ok().flatten() {
+ Some(a) => serde_json::from_str(&a.parameters).unwrap_or(Value::Null),
+ None => Value::Null,
}
}
diff --git a/src/server/telegram/mod.rs b/src/server/telegram/mod.rs
index 373b76b7..812a271b 100644
--- a/src/server/telegram/mod.rs
+++ b/src/server/telegram/mod.rs
@@ -489,7 +489,9 @@ async fn send_loop(state: AppState, runner: Arc<Runner>, mut rx: mpsc::Unbounded
}
if i + 1 == n {
if let Some(a) = &ask_id {
- let _ = state.db.telegram_ask_sent(a, tg_id).await;
+ if let Ok(Some(ask)) = state.db.telegram_ask_sent(a, tg_id).await {
+ bridge::ask_sent(&state, &runner, &ask, markup.as_ref()).await;
+ }
}
}
}
diff --git a/tests/delegation_test.rs b/tests/delegation_test.rs
index 707486b8..0cae31db 100644
--- a/tests/delegation_test.rs
+++ b/tests/delegation_test.rs
@@ -1730,6 +1730,12 @@ async fn the_65th_hand_off_pauses_and_continue_sends_it_once() {
assert_eq!(notice.text, "Paused after 64 hand-offs for one message: Builder not sent yet. Press Continue or say \"continue\" to carry on.");
wait_for("part 1 to finish", || async { delegation_status(&env, &ds[0].id).await == "completed" }).await;
+ // Press Continue in a later second than the 64 hand-offs above, as a person does. A message
+ // keeps its time to the second (CURRENT_TIMESTAMP) and a hand-off to the nanosecond, so a
+ // "continue" saved in the same second as the seeded rounds counts them all in its fresh
+ // allowance and the correction below re-pauses (CI on 3a0274a9, 2026-11-12)
+ let into_second = u64::from(chrono::Utc::now().timestamp_subsec_millis().min(999));
+ tokio::time::sleep(Duration::from_millis(1050 - into_second)).await;
let (s, v) = call(&env.app, "POST", &format!("/api/chains/{}/continue", notice.id), None).await;
assert_eq!(s, StatusCode::OK, "{v}");
wait_for("the 65th", || async { to_builder().await.len() >= 2 }).await;
diff --git a/tests/dev_autodetect_test.rs b/tests/dev_autodetect_test.rs
index d4347334..fb03157c 100644
--- a/tests/dev_autodetect_test.rs
+++ b/tests/dev_autodetect_test.rs
@@ -286,21 +286,21 @@ fn seed(gh: &MockGithub, r: &str) {
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");
+ let merged = commit(&sha(2), "Retry the upload (#5)", person, &[&sha(1)], &hours_ago(2));
+ let direct = commit(&sha(1), "Fix the README", person, &[], &hours_ago(3));
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(2)), json!([pull(5, "Retry the upload", ("retry", &sha(9)), "main", "demo-person", Some((&sha(2), &hours_ago(2))))]))
.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/{}", sha(3)), commit(&sha(3), "Add a cache", person, &[&sha(2)], &hours_ago(1)))
.json(&format!("{r}/commits/{}/check-runs", sha(3)), check_runs(&[("rust", "completed", Some("success"))]));
}
diff --git a/tests/dev_forges_test.rs b/tests/dev_forges_test.rs
index 8cc86e8e..f80552ad 100644
--- a/tests/dev_forges_test.rs
+++ b/tests/dev_forges_test.rs
@@ -106,7 +106,7 @@ fn mr(iid: u64, title: &str, head: (&str, &str), base: &str, draft: bool) -> Val
"iid": iid, "title": title, "description": "What it does.", "draft": draft, "state": "opened",
"web_url": format!("https://gitlab.example.com/group/app/-/merge_requests/{iid}"),
"author": {"username": "ana"}, "source_branch": head.0, "sha": head.1, "target_branch": base,
- "updated_at": "2026-11-06T10:00:00Z", "merged_at": null, "merge_commit_sha": null,
+ "updated_at": hours_ago(1), "merged_at": null, "merge_commit_sha": null,
})
}
@@ -115,7 +115,7 @@ fn pr(number: u64, title: &str, head: (&str, &str), base: &str) -> Value {
"number": number, "title": title, "body": "What it does.", "state": "open",
"html_url": format!("https://codeberg.example.com/org/app/pulls/{number}"),
"user": {"login": "ana"}, "head": {"ref": head.0, "sha": head.1}, "base": {"ref": base},
- "merged": false, "merged_at": null, "merge_commit_sha": null, "updated_at": "2026-11-06T10:00:00Z",
+ "merged": false, "merged_at": null, "merge_commit_sha": null, "updated_at": hours_ago(1),
})
}
@@ -151,7 +151,7 @@ async fn gitlab_merge_requests_get_review_cards_with_pipelines() {
// The root commit came from a merged MR
let mut merged = mr(5, "Start the repo", ("start", &root), "main", false);
merged["state"] = json!("merged");
- merged["merged_at"] = json!("2026-11-05T09:00:00Z");
+ merged["merged_at"] = json!(hours_ago(26));
merged["merge_commit_sha"] = json!(root);
merged["merge_user"] = json!({"username": "lin"});
mock.json(&format!("{p}/repository/commits/{root}/merge_requests"), json!([merged]));
@@ -238,7 +238,7 @@ async fn gitea_pull_requests_get_review_cards_with_statuses() {
);
let mut merged = pr(2, "Start the repo", ("start", &root), "main");
merged["merged"] = json!(true);
- merged["merged_at"] = json!("2026-11-05T09:00:00Z");
+ merged["merged_at"] = json!(hours_ago(26));
merged["merge_commit_sha"] = json!(root);
merged["merged_by"] = json!({"login": "lin"});
mock.json(&format!("{r}/commits/{root}/pull"), merged);
diff --git a/tests/dev_github_test.rs b/tests/dev_github_test.rs
index 6b01c575..28122336 100644
--- a/tests/dev_github_test.rs
+++ b/tests/dev_github_test.rs
@@ -122,7 +122,7 @@ async fn a_lost_base_commit_falls_back_to_the_newest() {
let gh = MockGithub::start(&PORTS).await;
let token = canary_token();
gh.require_token(&token);
- let list: Vec<Value> = (2..=4).rev().map(|n| commit(&sha(n), &format!("Change {n}"), ("Demo Person", "[email protected]"), &[], "2026-11-05T01:00:00Z")).collect();
+ let list: Vec<Value> = (2..=4).rev().map(|n| commit(&sha(n), &format!("Change {n}"), ("Demo Person", "[email protected]"), &[], &hours_ago(3))).collect();
gh.json(&format!("{R}/commits"), Value::Array(list)).fault(&format!("{R}/commits/{}", sha(1)), Fault::MissingBase);
let c = client(&gh, &token);
@@ -187,8 +187,8 @@ fn seed(gh: &MockGithub) {
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");
+ let merged = commit(&sha(2), "Retry the upload (#5)", person, &[&sha(1)], &hours_ago(2));
+ let direct = commit(&sha(1), "Fix the README", person, &[], &hours_ago(3));
gh.json("/user", user("demo-person"))
.json(R, repo(REPO, "main"))
.json(&format!("{R}/branches/main"), json!({"name": "main"}))
@@ -197,14 +197,14 @@ fn seed(gh: &MockGithub) {
.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(2)), json!([pull(5, "Retry the upload", ("retry", &sha(9)), "main", "demo-person", Some((&sha(2), &hours_ago(2))))]))
.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("failure"))]))
.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/{}", sha(3)), commit(&sha(3), "Add a cache", person, &[&sha(2)], &hours_ago(1)))
.json(&format!("{R}/commits/{}/check-runs", sha(3)), check_runs(&[("rust", "in_progress", None)]));
}
diff --git a/tests/dev_stale_guard_test.rs b/tests/dev_stale_guard_test.rs
index 738fabbd..6c8b4619 100644
--- a/tests/dev_stale_guard_test.rs
+++ b/tests/dev_stale_guard_test.rs
@@ -49,7 +49,7 @@ async fn a_review_that_finishes_after_its_pr_merged_stays_stale() {
let patch = "@@ -1,2 +1,2 @@\n-let retries = 1;\n+let retries = 3;";
let green = check_runs(&[("rust", "completed", Some("success"))]);
- let direct = commit(&sha(1), "Fix the README", person, &[], "2026-11-05T01:00:00Z");
+ let direct = commit(&sha(1), "Fix the README", person, &[], &hours_ago(3));
gh.json("/user", user("demo-person"))
.json(R, repo(REPO, "main"))
.json(&format!("{R}/branches/main"), json!({"name": "main"}))
@@ -65,7 +65,7 @@ async fn a_review_that_finishes_after_its_pr_merged_stays_stale() {
.json(&format!("{R}/commits/{}/check-runs", sha(1)), green.clone());
let head = sha(9);
gh.json(&format!("{R}/pulls/5/files"), json!([file("src/f5.rs", "modified", patch)]))
- .json(&format!("{R}/commits/{head}"), commit(&head, "Retry the upload", person, &[&sha(1)], "2026-11-05T02:00:00Z"))
+ .json(&format!("{R}/commits/{head}"), commit(&head, "Retry the upload", person, &[&sha(1)], &hours_ago(2)))
.json(&format!("{R}/commits/{head}/check-runs"), green.clone())
.json(&format!("{R}/pulls"), json!([pull(5, "Retry the upload", ("topic", &head), "main", "demo-person", None)]));
@@ -89,11 +89,11 @@ async fn a_review_that_finishes_after_its_pr_merged_stays_stale() {
// Poll 2: PR #5 merges, and the poller stales its review
let merge = sha(2);
- let c = commit(&merge, "Retry the upload (#5)", person, &[&sha(1)], "2026-11-05T03:00:00Z");
+ let c = commit(&merge, "Retry the upload (#5)", person, &[&sha(1)], &hours_ago(1));
let mut full = c.clone();
full["files"] = json!([file("src/f5.rs", "modified", patch)]);
gh.json(&format!("{R}/commits/{merge}"), full)
- .json(&format!("{R}/commits/{merge}/pulls"), json!([pull(5, "Retry the upload", ("topic", &head), "main", "demo-person", Some((&merge, "2026-11-05T03:00:00Z")))]))
+ .json(&format!("{R}/commits/{merge}/pulls"), json!([pull(5, "Retry the upload", ("topic", &head), "main", "demo-person", Some((&merge, &hours_ago(1))))]))
.json(&format!("{R}/commits/{merge}/check-runs"), green.clone())
.json(&format!("{R}/commits"), json!([c, direct.clone()]))
.json(&format!("{R}/pulls"), json!([]));
diff --git a/tests/dev_team_repos_test.rs b/tests/dev_team_repos_test.rs
index 3ba0e2a7..1e20eba6 100644
--- a/tests/dev_team_repos_test.rs
+++ b/tests/dev_team_repos_test.rs
@@ -32,7 +32,7 @@ fn seed(gh: &MockGithub, name: &str) {
let person = ("Lin (kwant bot)", "[email protected]");
let patch = "@@ -1,2 +1,2 @@\n-let retries = 1;\n+let retries = 3;";
let green = check_runs(&[("rust", "completed", Some("success"))]);
- let mut first = commit(&sha(1), "Fix the README", person, &[], "2026-11-05T01:00:00Z");
+ let mut first = commit(&sha(1), "Fix the README", person, &[], &hours_ago(3));
gh.json(&r, repo(name, "main"))
.json(&format!("{r}/contents"), json!([{"name": "Cargo.toml", "type": "file"}]))
.json(&format!("{r}/branches/main"), json!({"name": "main"}))
@@ -45,7 +45,7 @@ fn seed(gh: &MockGithub, name: &str) {
.json(&format!("{r}/pulls"), json!([pull(12, "Add a cache", ("cache", &sha(3)), "main", "demo-person", None)]))
.json(&format!("{r}/pulls/12"), pull(12, "Add a cache", ("cache", &sha(3)), "main", "demo-person", None))
.json(&format!("{r}/pulls/12/files"), json!([file("src/cache.rs", "modified", patch)]))
- .json(&format!("{r}/commits/{}", sha(3)), commit(&sha(3), "Add a cache", person, &[&sha(1)], "2026-11-05T03:00:00Z"))
+ .json(&format!("{r}/commits/{}", sha(3)), commit(&sha(3), "Add a cache", person, &[&sha(1)], &hours_ago(1)))
.json(&format!("{r}/commits/{}/check-runs", sha(3)), green);
}
diff --git a/tests/dev_verified_test.rs b/tests/dev_verified_test.rs
index b4d3319f..557e9995 100644
--- a/tests/dev_verified_test.rs
+++ b/tests/dev_verified_test.rs
@@ -55,7 +55,7 @@ async fn a_merged_pr_takes_its_reviewer_from_the_review_of_the_merged_head() {
let patch = "@@ -1,2 +1,2 @@\n-let retries = 1;\n+let retries = 3;";
let green = check_runs(&[("rust", "completed", Some("success"))]);
- let direct = commit(&sha(1), "Fix the README", person, &[], "2026-11-05T01:00:00Z");
+ let direct = commit(&sha(1), "Fix the README", person, &[], &hours_ago(3));
gh.json("/user", user("demo-person"))
.json(R, repo(REPO, "main"))
.json(&format!("{R}/branches/main"), json!({"name": "main"}))
@@ -73,7 +73,7 @@ async fn a_merged_pr_takes_its_reviewer_from_the_review_of_the_merged_head() {
let open = [(5, "Retry the upload", sha(9)), (6, "Add a cache", sha(7)), (7, "Tidy the logs", sha(6))];
for (n, title, head) in &open {
gh.json(&format!("{R}/pulls/{n}/files"), json!([file(&format!("src/f{n}.rs"), "modified", patch)]))
- .json(&format!("{R}/commits/{head}"), commit(head, title, person, &[&sha(1)], "2026-11-05T02:00:00Z"))
+ .json(&format!("{R}/commits/{head}"), commit(head, title, person, &[&sha(1)], &hours_ago(2)))
.json(&format!("{R}/commits/{head}/check-runs"), green.clone());
}
gh.json(&format!("{R}/pulls"), Value::Array(open.iter().map(|(n, t, h)| pull(*n, t, ("topic", h), "main", "demo-person", None)).collect()));
@@ -102,11 +102,11 @@ async fn a_merged_pr_takes_its_reviewer_from_the_review_of_the_merged_head() {
let mut list = vec![direct.clone()];
for (n, merge, head) in &merges {
let title = open.iter().find(|o| o.0 == *n).unwrap().1;
- let c = commit(merge, &format!("{title} (#{n})"), person, &[&sha(1)], "2026-11-05T03:00:00Z");
+ let c = commit(merge, &format!("{title} (#{n})"), person, &[&sha(1)], &hours_ago(1));
let mut full = c.clone();
full["files"] = json!([file(&format!("src/f{n}.rs"), "modified", patch)]);
gh.json(&format!("{R}/commits/{merge}"), full)
- .json(&format!("{R}/commits/{merge}/pulls"), json!([pull(*n, title, ("topic", head), "main", "demo-person", Some((merge, "2026-11-05T03:00:00Z")))]))
+ .json(&format!("{R}/commits/{merge}/pulls"), json!([pull(*n, title, ("topic", head), "main", "demo-person", Some((merge, &hours_ago(1))))]))
.json(&format!("{R}/commits/{merge}/check-runs"), green.clone());
list.insert(0, c);
}
diff --git a/tests/support/mock_github.rs b/tests/support/mock_github.rs
index 213c745f..11b45343 100644
--- a/tests/support/mock_github.rs
+++ b/tests/support/mock_github.rs
@@ -347,6 +347,17 @@ pub fn file(name: &str, status: &str, patch: &str) -> Value {
json!({"filename": name, "status": status, "additions": adds, "deletions": dels, "patch": patch})
}
+/// An RFC 3339 time `hours` hours before one moment fixed for the whole test run, as GitHub
+/// writes it. Dev mode reviews a branch or PR only while it is fresh (`KWANT_DEV_REVIEW_DAYS`, 7
+/// days by default, [`kwnt::server::dev::poller::is_fresh`]), so a hard-coded date turns every
+/// review card off a week after the test was written (2026-11-05 fixtures did on 2026-11-12).
+/// One base for every call keeps fixtures in the same order and spacing.
+pub fn hours_ago(hours: i64) -> String {
+ static BASE: std::sync::OnceLock<chrono::DateTime<chrono::Utc>> = std::sync::OnceLock::new();
+ let base = *BASE.get_or_init(chrono::Utc::now);
+ (base - chrono::Duration::hours(hours)).format("%Y-%m-%dT%H:%M:%SZ").to_string()
+}
+
/// A pull request; `merged` gives `(merge_commit_sha, merged_at)`.
pub fn pull(number: u64, title: &str, head: (&str, &str), base: &str, author: &str, merged: Option<(&str, &str)>) -> Value {
json!({
@@ -355,7 +366,7 @@ pub fn pull(number: u64, title: &str, head: (&str, &str), base: &str, author: &s
"user": user(author),
"head": {"ref": head.0, "sha": head.1}, "base": {"ref": base, "sha": "0000000000000000000000000000000000000000"},
"merged_at": merged.map(|m| m.1), "merge_commit_sha": merged.map(|m| m.0),
- "merged_by": merged.map(|_| user("demo-person")), "updated_at": "2026-11-05T03:00:00Z",
+ "merged_by": merged.map(|_| user("demo-person")), "updated_at": hours_ago(1),
})
}
diff --git a/tests/telegram_test.rs b/tests/telegram_test.rs
index c95c1a7a..09b51c9c 100644
--- a/tests/telegram_test.rs
+++ b/tests/telegram_test.rs
@@ -532,6 +532,35 @@ async fn a_changed_card_or_the_switch_going_off_makes_it_link_only() {
assert!(edit.text().contains("Approve it in kwant."));
}
+/// Regression (CI on cdfa2017, 2026-11-12): a card still on its way to Telegram when the switch goes
+/// off has no message id yet, so the switch-off sweep can't edit it. It used to keep its Allow once
+/// button (a dead one: the tap was refused); the sender now makes it link-only once its id is stored.
+#[tokio::test]
+async fn a_card_on_its_way_when_the_switch_goes_off_is_made_link_only_once_sent() {
+ let env = setup().await;
+ let tg = mock_telegram::shared();
+ let bot = paired(&env, tg, 45).await;
+ let (s, _) = call(&env.app, "PATCH", BASE, Some(json!({"allow_approvals": true}))).await;
+ assert_eq!(s, StatusCode::OK);
+
+ // Telegram holds the card back for a second (429, retry_after 1): sent armed, no id yet
+ tg.fault(&bot, "sendMessage", 429, 1);
+ let (_, _rx) = approval(&env, json!({"source": "mcp", "tool": "third", "server": "files"})).await;
+ tg.wait_send(&bot, |c| c.text().contains("<code>third</code>") && c.body.get("__sent_id").is_none()).await;
+ let (s, _) = call(&env.app, "PATCH", BASE, Some(json!({"allow_approvals": false}))).await;
+ assert_eq!(s, StatusCode::OK);
+
+ let card = tg.wait_send(&bot, |c| c.text().contains("<code>third</code>") && c.body.get("__sent_id").is_some()).await;
+ assert_eq!(card.callbacks().len(), 1, "it went out with Allow once: {:?}", card.buttons());
+ let edit = tg.wait_edit(&bot, |c| c.message_id() == card.message_id()).await;
+ assert!(edit.callbacks().is_empty(), "{:?}", edit.buttons());
+ assert!(edit.text().contains("Approve it in kwant."), "{}", edit.text());
+ // Edited once, whichever of the sweep and the sender saw the id
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ let edits = tg.calls_of(&bot, "editMessageText").into_iter().filter(|c| c.message_id() == card.message_id()).count();
+ assert_eq!(edits, 1);
+}
+
#[tokio::test]
async fn bash_production_marks_and_crossed_taps_stay_link_only() {
let env = setup().await;