Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6eb29ca19d | ||
|
|
707c9fc4cd | ||
|
|
5e2454ae3d | ||
|
|
9913a202ec | ||
|
|
738b39584d | ||
|
|
ccad2c1f6e | ||
|
|
45503de195 | ||
|
|
486c49d50b |
No files matched your search
@@ -3,6 +3,29 @@
|
||||
All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/);
|
||||
until 1.0, minor versions may contain breaking changes.
|
||||
|
||||
## [v202611-00065] – 2026-11-19
|
||||
|
||||
### Added
|
||||
|
||||
- **Terminal client for Linux riscv64** – built with every release alongside x86_64 and aarch64; `install.sh` and `codecraft update` pick it up (`/cli/download/linux-riscv64`).
|
||||
|
||||
## [v202611-00064] – 2026-11-19
|
||||
|
||||
### Added
|
||||
|
||||
- **Factory: Telegram message when an issue needs you** – a question from the review (with the questions) or a failure (build blocked, build/acceptance failed, rework limit reached) is sent to the paired Telegram chat, in the language of your web UI, with a link to the issue. Nothing is sent without a paired bot. (v202611-00063 was tagged but never built; this ships with the next release.)
|
||||
- **Telegram notification settings** (Settings → Telegram): a switch for the factory alerts and a **night mode** (default 22:00–06:00, adjustable, server time) in which nothing is sent on CodeCraft's own initiative – no factory alerts and no approvals/questions from other chats; the chat you are talking to in Telegram keeps answering. Held-back messages are not repeated later.
|
||||
|
||||
## [v202611-00062] – 2026-11-18
|
||||
|
||||
### Added
|
||||
|
||||
- **Factory: remove issues from the board** – a "Remove from board" button for issues that are not running, and issues deleted on the forge (404) disappear from the board by themselves at the next poll.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Factory: the "parallel" limit was exceeded** – phases were counted by their run rows, which appear only after the checkout, so one poll could start more phases than allowed (2 allowed, 4 running). They are now counted by issue state, which is set before a phase starts.
|
||||
|
||||
## [v202611-00061] – 2026-11-18
|
||||
|
||||
### Changed
|
||||
|
||||
+5
-3
@@ -52,7 +52,7 @@ RUN touch core/src/lib.rs server/src/main.rs \
|
||||
&& cargo zigbuild --release -p codecraft --target "$(cat /target).2.36" \
|
||||
&& cp "target/$(cat /target)/release/codecraft" /codecraft
|
||||
|
||||
# --- terminal client (static Linux binaries for x86_64 and aarch64) -----------
|
||||
# --- terminal client (static Linux binaries for x86_64, aarch64 and riscv64) -----------
|
||||
# Served by the server for download (/cli/install.sh, codecraft update).
|
||||
FROM toolchain AS cli
|
||||
COPY Cargo.toml Cargo.lock ./
|
||||
@@ -62,10 +62,12 @@ COPY server/resources ./server/resources
|
||||
COPY cli ./cli
|
||||
ARG CODECRAFT_VERSION=""
|
||||
ENV CODECRAFT_VERSION=${CODECRAFT_VERSION}
|
||||
RUN rustup target add riscv64gc-unknown-linux-musl
|
||||
RUN mkdir -p server/src && echo 'fn main(){}' > server/src/main.rs \
|
||||
&& cargo zigbuild --release -p codecraft-cli --target x86_64-unknown-linux-musl --target aarch64-unknown-linux-musl \
|
||||
&& cargo zigbuild --release -p codecraft-cli --target x86_64-unknown-linux-musl --target aarch64-unknown-linux-musl --target riscv64gc-unknown-linux-musl \
|
||||
&& mkdir -p /out && cp target/x86_64-unknown-linux-musl/release/codecraft /out/codecraft-linux-x86_64 \
|
||||
&& cp target/aarch64-unknown-linux-musl/release/codecraft /out/codecraft-linux-aarch64
|
||||
&& cp target/aarch64-unknown-linux-musl/release/codecraft /out/codecraft-linux-aarch64 \
|
||||
&& cp target/riscv64gc-unknown-linux-musl/release/codecraft /out/codecraft-linux-riscv64
|
||||
|
||||
# --- Docker CLI (static client; the daemon is the host's via the mounted socket) --
|
||||
FROM toolchain AS dockercli
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img alt="Version v202611-00061" src="https://img.shields.io/badge/version-v202611--00061-d69e2e?style=flat-square">
|
||||
<img alt="Version v202611-00065" src="https://img.shields.io/badge/version-v202611--00065-d69e2e?style=flat-square">
|
||||
<img alt="License: MIT" src="https://img.shields.io/badge/license-MIT-689d6a?style=flat-square">
|
||||
<img alt="Rust backend" src="https://img.shields.io/badge/backend-Rust-b7410e?style=flat-square&logo=rust">
|
||||
<img alt="React PWA" src="https://img.shields.io/badge/frontend-React%20PWA-2d81ff?style=flat-square&logo=react">
|
||||
@@ -205,12 +205,12 @@ Anthropic, OpenAI, Gemini, OpenRouter, opencode or a local model server (Ollama,
|
||||
llama.cpp, vLLM – detected automatically); both can be mixed.
|
||||
|
||||
```sh
|
||||
curl -fsSL https://<your-codecraft-server>/cli/install.sh | sh # Linux x86_64 / aarch64
|
||||
curl -fsSL https://<your-codecraft-server>/cli/install.sh | sh # Linux x86_64 / aarch64 / riscv64
|
||||
codecraft login # server URL, user name, password → creates an API token
|
||||
codecraft # start in the current folder; /help lists the commands
|
||||
```
|
||||
|
||||
The Docker image ships static binaries for Linux x86_64 and aarch64; the server offers them
|
||||
The Docker image ships static binaries for Linux x86_64, aarch64 and riscv64; the server offers them
|
||||
for download (*Settings → Account*) and `codecraft update` fetches new versions from it. Other
|
||||
platforms: `cargo install --locked --git https://git.familie-zink.org/zink/codecraft codecraft-cli`.
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ arch=$(uname -m)
|
||||
case "$arch" in
|
||||
x86_64|amd64) arch=x86_64 ;;
|
||||
aarch64|arm64) arch=aarch64 ;;
|
||||
riscv64) arch=riscv64 ;;
|
||||
*) echo "codecraft: unsupported architecture $arch" >&2; exit 1 ;;
|
||||
esac
|
||||
case "$os" in
|
||||
|
||||
+57
-2
@@ -176,6 +176,7 @@ pub fn router(app: AppState) -> Router {
|
||||
.route("/factory/release/preview", get(factory_release_preview))
|
||||
.route("/factory/release", post(factory_release))
|
||||
.route("/factory/issues/close", post(factory_close_issue))
|
||||
.route("/factory/issues/remove", post(factory_remove_issue))
|
||||
.route("/factory/issues/pr", get(factory_pr))
|
||||
.route("/factory/issues/pr/merge", post(factory_pr_merge))
|
||||
.route("/account/factory/connection/test", post(test_factory_connection))
|
||||
@@ -190,6 +191,7 @@ pub fn router(app: AppState) -> Router {
|
||||
.route("/account/memory", get(crate::cli_api::get_memory).put(crate::cli_api::put_memory))
|
||||
.route("/account/modes", get(get_personal_modes).put(put_personal_modes))
|
||||
.route("/account/telegram", get(get_telegram).put(put_telegram).delete(delete_telegram))
|
||||
.route("/account/telegram/prefs", put(put_telegram_prefs))
|
||||
.route("/templates", get(crate::cli_api::get_templates))
|
||||
.route("/templates/{scope}", put(crate::cli_api::put_templates))
|
||||
.route("/cli/config", get(crate::cli_api::config))
|
||||
@@ -434,12 +436,52 @@ async fn get_telegram(Extension(user): Extension<User>, State(app): State<AppSta
|
||||
"configured": !s.token.is_empty(),
|
||||
"bot": s.bot,
|
||||
"paired": s.chat_id.is_some(),
|
||||
"pair_code": if s.chat_id.is_none() { s.pair_code } else { String::new() },
|
||||
"pair_code": if s.chat_id.is_none() { s.pair_code.clone() } else { String::new() },
|
||||
"running": running,
|
||||
"error": error,
|
||||
"factory_alerts": !s.factory_alerts_off,
|
||||
"quiet": s.quiet,
|
||||
"quiet_from": if s.quiet_from.is_empty() { "22:00".to_string() } else { s.quiet_from.clone() },
|
||||
"quiet_to": if s.quiet_to.is_empty() { "06:00".to_string() } else { s.quiet_to.clone() },
|
||||
"quiet_now": s.quiet_now(),
|
||||
"server_time": chrono::Local::now().format("%H:%M").to_string(),
|
||||
})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TelegramPrefs {
|
||||
factory_alerts: Option<bool>,
|
||||
quiet: Option<bool>,
|
||||
quiet_from: Option<String>,
|
||||
quiet_to: Option<String>,
|
||||
}
|
||||
|
||||
/// Notification preferences: factory alerts on/off and the night mode.
|
||||
async fn put_telegram_prefs(Extension(user): Extension<User>, State(app): State<AppState>, Json(b): Json<TelegramPrefs>) -> ApiResult {
|
||||
let mut s = crate::telegram::load(&app, &user.id);
|
||||
for (v, what) in [(&b.quiet_from, "from"), (&b.quiet_to, "to")] {
|
||||
if let Some(t) = v {
|
||||
if crate::telegram::parse_hhmm(t).is_none() {
|
||||
return Err(ApiError(StatusCode::BAD_REQUEST, format!("invalid time ({what}) – use HH:MM")));
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(v) = b.factory_alerts {
|
||||
s.factory_alerts_off = !v;
|
||||
}
|
||||
if let Some(v) = b.quiet {
|
||||
s.quiet = v;
|
||||
}
|
||||
if let Some(v) = b.quiet_from {
|
||||
s.quiet_from = v.trim().to_string();
|
||||
}
|
||||
if let Some(v) = b.quiet_to {
|
||||
s.quiet_to = v.trim().to_string();
|
||||
}
|
||||
app.store.set_user_setting(&user.id, "telegram", &s)?;
|
||||
get_telegram(Extension(user), State(app)).await
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TelegramBody {
|
||||
token: String,
|
||||
@@ -450,7 +492,9 @@ async fn put_telegram(Extension(user): Extension<User>, State(app): State<AppSta
|
||||
let token = crate::telegram::extract_token(&b.token)
|
||||
.ok_or_else(|| ApiError(StatusCode::BAD_REQUEST, "that is not a bot token – it looks like 123456789:AAH… (paste only the token from @BotFather)".into()))?;
|
||||
let bot = crate::telegram::check_token(&token).await.map_err(|e| ApiError(StatusCode::BAD_REQUEST, format!("token rejected by Telegram: {e:#}")))?;
|
||||
let s = crate::telegram::Settings { token, bot, pair_code: crate::telegram::new_pair_code(), ..Default::default() };
|
||||
let old = crate::telegram::load(&app, &user.id);
|
||||
// Notification preferences survive a new bot.
|
||||
let s = crate::telegram::Settings { token, bot, pair_code: crate::telegram::new_pair_code(), factory_alerts_off: old.factory_alerts_off, quiet: old.quiet, quiet_from: old.quiet_from, quiet_to: old.quiet_to, ..Default::default() };
|
||||
app.store.set_user_setting(&user.id, "telegram", &s)?;
|
||||
crate::telegram::restart(&app, &user.id);
|
||||
app.audit(Some(&user), "telegram.connect", &s.bot, "");
|
||||
@@ -2836,6 +2880,17 @@ async fn factory_close_issue(Extension(user): Extension<User>, State(app): State
|
||||
Ok(Json(json!({"ok": true})))
|
||||
}
|
||||
|
||||
/// Take an issue off the factory board (the issue on the forge is not touched). Not while a phase runs.
|
||||
async fn factory_remove_issue(Extension(user): Extension<User>, State(app): State<AppState>, headers: axum::http::HeaderMap, Json(b): Json<CloseIssue>) -> ApiResult {
|
||||
let (_, row) = factory_issue_forge(&app, &user, &b.repo, b.number)?;
|
||||
if matches!(row["state"].as_str(), Some("review" | "building" | "testing")) {
|
||||
return Err(ApiError(StatusCode::BAD_REQUEST, "a phase is running – wait for it to end or stop it first".into()));
|
||||
}
|
||||
app.store.factory_issue_delete(&b.repo, b.number)?;
|
||||
app.audit(Some(&user), "factory.issue.remove", &format!("{}#{}", b.repo, b.number), &crate::auth::client_ip(&headers));
|
||||
Ok(Json(json!({"ok": true})))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PrQuery {
|
||||
repo: String,
|
||||
|
||||
@@ -562,6 +562,14 @@ impl Forge {
|
||||
Ok(!matches!(v["state"].as_str(), Some("closed")))
|
||||
}
|
||||
|
||||
/// Has the issue been deleted on the forge (404)? Other errors (network, token) count as "still there".
|
||||
pub async fn issue_gone(&self, number: u64) -> bool {
|
||||
match self.call(reqwest::Method::GET, self.rp(&format!("/issues/{number}")), None).await {
|
||||
Err(e) => e.to_string().contains("404"),
|
||||
Ok(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn close_issue(&self, number: u64) -> Result<()> {
|
||||
match self.kind {
|
||||
Kind::Gitlab => self.call(reqwest::Method::PUT, self.rp(&format!("/issues/{number}")), Some(json!({"state_event": "close"}))).await.map(|_| ()),
|
||||
@@ -966,6 +974,7 @@ async fn review(app: Arc<App>, user: User, cfg: RepoCfg, issue: Value, comments:
|
||||
let qs: Vec<String> = res["questions"].as_array().map(|a| a.iter().filter_map(|q| q.as_str().map(|q| format!("- {q}"))).collect()).unwrap_or_default();
|
||||
set(&[("state", json!("question")), ("note", json!(summary))]);
|
||||
let _ = g.set_labels(n as u64, &status_labels(&cfg, "question")).await;
|
||||
alert(&app, &cfg.url, n, "question", &if qs.is_empty() { summary.clone() } else { qs.join("\n") }).await;
|
||||
bot_comment(&g, n as u64, &format!("**Review: questions before this can be built.** {summary}\n\n{}\n\nAnswer in a comment; the review starts again automatically.", qs.join("\n"))).await;
|
||||
// Remember the newest comment (including this one) so only later answers count.
|
||||
if let Ok(all) = g.comments(n as u64).await {
|
||||
@@ -1059,6 +1068,7 @@ async fn build_fail(app: &Arc<App>, g: &Forge, cfg: &RepoCfg, n: i64, why: &str)
|
||||
if attempts >= cfg.build.max_attempts {
|
||||
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("failed")), ("attempts", json!(attempts)), ("note", json!(why))]);
|
||||
let _ = g.set_labels(n as u64, &status_labels(cfg, "failed")).await;
|
||||
alert(&app, &cfg.url, n, "failed", &why).await;
|
||||
bot_comment(g, n as u64, &format!("**Build failed:** {why}.")).await;
|
||||
} else {
|
||||
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("approved")), ("attempts", json!(attempts)), ("note", json!(why))]);
|
||||
@@ -1103,6 +1113,7 @@ async fn build(app: Arc<App>, user: User, cfg: RepoCfg, issue: Value, comments:
|
||||
let reason = res["reason"].as_str().unwrap_or(&summary).trim().to_string();
|
||||
set(&[("state", json!("failed")), ("note", json!(reason))]);
|
||||
let _ = g.set_labels(n as u64, &status_labels(&cfg, "failed")).await;
|
||||
alert(&app, &cfg.url, n, "failed", &reason).await;
|
||||
bot_comment(&g, n as u64, &format!("**Build: cannot be built as specified.** {reason}")).await;
|
||||
notify(&app, &user, &format!("Factory #{n}"), &format!("build blocked – {reason}"), n).await;
|
||||
return;
|
||||
@@ -1169,6 +1180,7 @@ async fn qa_fail(app: &Arc<App>, g: &Forge, cfg: &RepoCfg, n: i64, why: &str) {
|
||||
if attempts >= cfg.qa.max_attempts {
|
||||
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("failed")), ("attempts", json!(attempts)), ("note", json!(why))]);
|
||||
let _ = g.set_labels(n as u64, &status_labels(cfg, "failed")).await;
|
||||
alert(&app, &cfg.url, n, "failed", &why).await;
|
||||
bot_comment(g, n as u64, &format!("**Acceptance failed to run:** {why}.")).await;
|
||||
} else {
|
||||
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("qa")), ("attempts", json!(attempts)), ("note", json!(why))]);
|
||||
@@ -1243,6 +1255,7 @@ async fn qa(app: Arc<App>, user: User, cfg: RepoCfg, issue: Value) {
|
||||
if round >= cfg.max_rework {
|
||||
set(&[("state", json!("failed")), ("note", json!(findings.clone()))]);
|
||||
let _ = g.set_labels(n as u64, &status_labels(&cfg, "failed")).await;
|
||||
alert(&app, &cfg.url, n, "failed", &findings.clone()).await;
|
||||
bot_comment(&g, n as u64, &format!("**Acceptance failed after {} rework rounds.** {summary}\n\n{table}\n{findings}", cfg.max_rework)).await;
|
||||
notify(&app, &user, &format!("Factory #{n}"), "acceptance failed, rework limit reached", n).await;
|
||||
} else {
|
||||
@@ -1279,6 +1292,7 @@ async fn fail_or_retry(app: &Arc<App>, g: &Forge, cfg: &RepoCfg, n: i64, why: &s
|
||||
if attempts >= cfg.review.max_attempts {
|
||||
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("failed")), ("attempts", json!(attempts)), ("note", json!(why))]);
|
||||
let _ = g.set_labels(n as u64, &status_labels(cfg, "failed")).await;
|
||||
alert(&app, &cfg.url, n, "failed", &why).await;
|
||||
bot_comment(g, n as u64, &format!("**Failed:** {why}.")).await;
|
||||
} else {
|
||||
let _ = app.store.factory_issue_set(&cfg.url, n, &[("state", json!("new")), ("attempts", json!(attempts)), ("note", json!(why))]);
|
||||
@@ -1290,6 +1304,23 @@ pub(crate) async fn notify(app: &App, user: &User, title: &str, body: &str, issu
|
||||
let _ = crate::push::send_to_user(app, &user.id, &payload).await;
|
||||
}
|
||||
|
||||
/// Tell the user on Telegram (if paired) that an issue needs them: a question to answer or a failure.
|
||||
pub(crate) async fn alert(app: &App, repo: &str, n: i64, what: &str, detail: &str) {
|
||||
let Ok(Some(row)) = app.store.factory_issue(repo, n) else { return };
|
||||
let Some(owner) = row["owner_id"].as_str() else { return };
|
||||
let de = crate::telegram::german(app, owner);
|
||||
let name = repo.trim_end_matches(".git").rsplit('/').next().unwrap_or(repo);
|
||||
let head = match (what, de) {
|
||||
("question", true) => "❓ Frage zu",
|
||||
("question", false) => "❓ Question on",
|
||||
(_, true) => "❌ Fehlgeschlagen:",
|
||||
(_, false) => "❌ Failed:",
|
||||
};
|
||||
let detail: String = detail.trim().chars().take(600).collect();
|
||||
let text = format!("{head} {name} #{n} – {}\n\n{detail}\n\n{}/issues/{n}", row["title"].as_str().unwrap_or(""), repo.trim_end_matches(".git"));
|
||||
crate::telegram::notify_user(app, owner, &text).await;
|
||||
}
|
||||
|
||||
/// One pass over a repository: take up new issues, restart reviews after answers.
|
||||
pub async fn poll_repo(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()> {
|
||||
let g = Forge::new(cfg)?;
|
||||
@@ -1353,6 +1384,14 @@ pub async fn poll_repo(app: &Arc<App>, user: &User, cfg: &RepoCfg) -> Result<()>
|
||||
app.store.factory_issue_set(&cfg.url, n, &[("state", json!("closed"))])?;
|
||||
}
|
||||
}
|
||||
// Issues deleted on the forge leave the board (closed ones stay: they still exist there).
|
||||
for row in app.store.factory_issues(&user.id)?.into_iter().filter(|r| r["repo"].as_str() == Some(cfg.url.as_str()) && !matches!(r["state"].as_str(), Some("review" | "building" | "testing"))) {
|
||||
let n = issue_no(&row);
|
||||
if n > 0 && !open.contains(&n) && g.issue_gone(n as u64).await {
|
||||
tracing::info!("factory {}: #{n} was deleted on the forge – removed from the board", cfg.url);
|
||||
app.store.factory_issue_delete(&cfg.url, n)?;
|
||||
}
|
||||
}
|
||||
// Merged issues get their version and tag.
|
||||
if let Err(e) = crate::factory_version::version_pass(app, user, cfg).await {
|
||||
tracing::warn!("factory {}: versions: {e:#}", cfg.url);
|
||||
|
||||
+9
-1
@@ -1497,6 +1497,12 @@ impl Store {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove an issue from the factory board (runs and cost statistics stay).
|
||||
pub fn factory_issue_delete(&self, repo: &str, number: i64) -> Result<()> {
|
||||
self.conn.lock().unwrap().execute("DELETE FROM factory_issues WHERE repo_url = ?1 AND number = ?2", params![repo, number])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Update the given columns (whitelisted) of an issue.
|
||||
pub fn factory_issue_set(&self, repo: &str, number: i64, fields: &[(&str, Value)]) -> Result<()> {
|
||||
const COLS: [&str; 11] = ["title", "state", "attempts", "rounds", "last_comment", "scenarios", "branch", "pr_url", "note", "author", "version"];
|
||||
@@ -1586,7 +1592,9 @@ impl Store {
|
||||
}
|
||||
|
||||
pub fn factory_running(&self, repo: &str) -> Result<i64> {
|
||||
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_runs WHERE repo_url = ?1 AND status = 'running'", [repo], |r| r.get(0))?)
|
||||
// Counted by issue state, not by run rows: the state is set before the phase is spawned, the run row
|
||||
// only once its checkout is done – counting runs let a single poll start more phases than allowed.
|
||||
Ok(self.conn.lock().unwrap().query_row("SELECT COUNT(*) FROM factory_issues WHERE repo_url = ?1 AND state IN ('review', 'building', 'testing')", [repo], |r| r.get(0))?)
|
||||
}
|
||||
|
||||
/// Runs with token and cost totals (joined from the usage table).
|
||||
|
||||
@@ -51,6 +51,48 @@ pub struct Settings {
|
||||
/// Reasoning effort for the next messages (/effort).
|
||||
#[serde(default)]
|
||||
pub effort: Option<String>,
|
||||
/// No factory alerts (question / failed) on Telegram. Inverted so that the default is "on".
|
||||
#[serde(default)]
|
||||
pub factory_alerts_off: bool,
|
||||
/// Night mode: no unsolicited messages between `quiet_from` and `quiet_to` (server time).
|
||||
#[serde(default)]
|
||||
pub quiet: bool,
|
||||
/// "HH:MM"; empty = 22:00.
|
||||
#[serde(default)]
|
||||
pub quiet_from: String,
|
||||
/// "HH:MM"; empty = 06:00.
|
||||
#[serde(default)]
|
||||
pub quiet_to: String,
|
||||
}
|
||||
|
||||
/// Minutes since midnight of an "HH:MM" string.
|
||||
pub fn parse_hhmm(s: &str) -> Option<u32> {
|
||||
let (h, m) = s.trim().split_once(':')?;
|
||||
let (h, m): (u32, u32) = (h.parse().ok()?, m.parse().ok()?);
|
||||
(h < 24 && m < 60).then_some(h * 60 + m)
|
||||
}
|
||||
|
||||
/// Is `now` (minutes since midnight) inside the quiet window? The window may span midnight.
|
||||
pub fn in_quiet_window(from: u32, to: u32, now: u32) -> bool {
|
||||
match from.cmp(&to) {
|
||||
std::cmp::Ordering::Equal => false,
|
||||
std::cmp::Ordering::Less => now >= from && now < to,
|
||||
std::cmp::Ordering::Greater => now >= from || now < to,
|
||||
}
|
||||
}
|
||||
|
||||
impl Settings {
|
||||
/// Night mode is on and it is night now.
|
||||
pub fn quiet_now(&self) -> bool {
|
||||
use chrono::Timelike;
|
||||
if !self.quiet {
|
||||
return false;
|
||||
}
|
||||
let from = parse_hhmm(if self.quiet_from.is_empty() { "22:00" } else { &self.quiet_from }).unwrap_or(22 * 60);
|
||||
let to = parse_hhmm(if self.quiet_to.is_empty() { "06:00" } else { &self.quiet_to }).unwrap_or(6 * 60);
|
||||
let t = chrono::Local::now();
|
||||
in_quiet_window(from, to, t.hour() * 60 + t.minute())
|
||||
}
|
||||
}
|
||||
|
||||
fn api_base() -> String {
|
||||
@@ -260,6 +302,18 @@ fn user(app: &App, user_id: &str) -> Result<User> {
|
||||
app.store.user(user_id)?.filter(|u| !u.disabled).ok_or_else(|| anyhow!("account disabled"))
|
||||
}
|
||||
|
||||
/// Send a message (HTML-escaped) to the user's paired Telegram chat; silent when there is none.
|
||||
pub async fn notify_user(app: &App, user_id: &str, text: &str) {
|
||||
let s = load(app, user_id);
|
||||
let (true, Some(chat)) = (!s.token.is_empty(), s.chat_id) else { return };
|
||||
if s.factory_alerts_off || s.quiet_now() {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = (Bot { token: s.token }).send(chat, &esc(text), None).await {
|
||||
tracing::warn!("telegram: notification not sent: {e:#}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The user reads German (language preference of the web UI).
|
||||
pub fn german(app: &App, user_id: &str) -> bool {
|
||||
let prefs: Value = app.store.user_setting(user_id, "prefs").unwrap_or_default();
|
||||
@@ -875,6 +929,10 @@ async fn listen(app: Arc<App>) {
|
||||
let Some(chat) = st.chat_id else { continue };
|
||||
let de = german(&app, &owner);
|
||||
let is_current = st.session.as_deref() == Some(session_id.as_str());
|
||||
// Night mode: only the chat the user is talking to in Telegram still reports.
|
||||
if !is_current && st.quiet_now() {
|
||||
continue;
|
||||
}
|
||||
// Chats with "not to Telegram": their approvals and questions stay in the web UI
|
||||
// (subagents follow their top-level chat; the chat open in Telegram always reports).
|
||||
if !is_current && matches!(ev, Event::PermissionRequest { .. } | Event::QuestionRequest { .. }) {
|
||||
@@ -1204,3 +1262,30 @@ mod tests {
|
||||
assert_eq!(step_line("todo_write", &json!({})), "todo_write");
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod quiet_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn quiet_window_spans_midnight() {
|
||||
let (from, to) = (parse_hhmm("22:00").unwrap(), parse_hhmm("06:00").unwrap());
|
||||
assert!(in_quiet_window(from, to, 23 * 60));
|
||||
assert!(in_quiet_window(from, to, 0));
|
||||
assert!(in_quiet_window(from, to, 5 * 60 + 59));
|
||||
assert!(!in_quiet_window(from, to, 6 * 60));
|
||||
assert!(!in_quiet_window(from, to, 12 * 60));
|
||||
assert!(!in_quiet_window(from, to, 21 * 60 + 59));
|
||||
assert!(in_quiet_window(from, to, 22 * 60));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quiet_window_within_a_day_and_degenerate() {
|
||||
assert!(in_quiet_window(13 * 60, 14 * 60, 13 * 60 + 30));
|
||||
assert!(!in_quiet_window(13 * 60, 14 * 60, 15 * 60));
|
||||
assert!(!in_quiet_window(600, 600, 600));
|
||||
assert_eq!(parse_hhmm("7:05"), Some(425));
|
||||
assert_eq!(parse_hhmm("24:00"), None);
|
||||
assert_eq!(parse_hhmm("x"), None);
|
||||
}
|
||||
}
|
||||
@@ -348,6 +348,20 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const removeIssue = async () => {
|
||||
if (!selected) return;
|
||||
if (!(await confirmDialog({ message: t("factory.removeConfirm", { n: selected.number }), confirmLabel: t("factory.remove"), danger: true }))) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
await post("/factory/issues/remove", { repo: selected.repo, number: selected.number });
|
||||
setSel("");
|
||||
await reload();
|
||||
} catch (e: any) {
|
||||
toast(e.message);
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const closeIssue = async () => {
|
||||
if (!selected) return;
|
||||
const comment = await promptDialog({ title: t("factory.closeTitle"), message: t("factory.closeMsg", { n: selected.number }), defaultValue: t("factory.closeDefault"), confirmLabel: t("factory.close") });
|
||||
@@ -503,6 +517,11 @@ function FactoryOverview({ onSettings }: { onSettings: () => void }) {
|
||||
</button>
|
||||
</>
|
||||
)}
|
||||
{selected && !["review", "building", "testing"].includes(selected.state) && (
|
||||
<button className="small" onClick={removeIssue} disabled={busy} title={t("factory.removeHint")}>
|
||||
<Icon name="trash" /> {t("factory.remove")}
|
||||
</button>
|
||||
)}
|
||||
{selected && selected.state === "done" && (
|
||||
<button className="small" onClick={closeIssue} disabled={busy}>
|
||||
<Icon name="check" /> {t("factory.close")}
|
||||
|
||||
@@ -43,7 +43,7 @@ export function CliInstall() {
|
||||
</ol>
|
||||
{prebuilt && (
|
||||
<div className="hint">
|
||||
{t("cli.downloads")} <a href="/cli/download/linux-x86_64">Linux x86_64</a> · <a href="/cli/download/linux-aarch64">Linux arm64</a>
|
||||
{t("cli.downloads")} <a href="/cli/download/linux-x86_64">Linux x86_64</a> · <a href="/cli/download/linux-aarch64">Linux arm64</a> · <a href="/cli/download/linux-riscv64">Linux riscv64</a>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -12,6 +12,12 @@ interface Status {
|
||||
pair_code: string;
|
||||
running: boolean;
|
||||
error?: string | null;
|
||||
factory_alerts: boolean;
|
||||
quiet: boolean;
|
||||
quiet_from: string;
|
||||
quiet_to: string;
|
||||
quiet_now: boolean;
|
||||
server_time: string;
|
||||
}
|
||||
|
||||
/** Connect a personal Telegram bot as a chat interface. */
|
||||
@@ -33,6 +39,14 @@ export function Telegram() {
|
||||
setBusy(false);
|
||||
}
|
||||
};
|
||||
const savePrefs = async (patch: Partial<Pick<Status, "factory_alerts" | "quiet" | "quiet_from" | "quiet_to">>) => {
|
||||
try {
|
||||
await put("/account/telegram/prefs", patch);
|
||||
reload();
|
||||
} catch (e) {
|
||||
toast(e);
|
||||
}
|
||||
};
|
||||
const disconnect = async () => {
|
||||
if (!(await confirmDialog({ message: t("telegram.disconnectConfirm"), danger: true, confirmLabel: t("telegram.disconnect") }))) return;
|
||||
await del("/account/telegram").catch((e) => toast(e));
|
||||
@@ -97,6 +111,22 @@ export function Telegram() {
|
||||
)}
|
||||
{data.error && <div className="notice err" style={{ marginTop: 10 }}>{data.error}</div>}
|
||||
{data.paired && <div className="hint" style={{ marginTop: 10 }}>{t("telegram.commands")}</div>}
|
||||
<h4 style={{ margin: "16px 0 6px" }}>{t("telegram.notify")}</h4>
|
||||
<label className="row" style={{ gap: 8, alignItems: "center" }}>
|
||||
<input type="checkbox" checked={data.factory_alerts} onChange={(e) => void savePrefs({ factory_alerts: e.target.checked })} />
|
||||
<span>{t("telegram.factoryAlerts")}</span>
|
||||
</label>
|
||||
<label className="row" style={{ gap: 8, alignItems: "center", marginTop: 6 }}>
|
||||
<input type="checkbox" checked={data.quiet} onChange={(e) => void savePrefs({ quiet: e.target.checked })} />
|
||||
<span>{t("telegram.quiet")}</span>
|
||||
</label>
|
||||
<div className="row" style={{ gap: 8, alignItems: "center", marginTop: 6, marginLeft: 24, flexWrap: "wrap", opacity: data.quiet ? 1 : 0.5 }}>
|
||||
<input type="time" value={data.quiet_from} disabled={!data.quiet} onChange={(e) => e.target.value && void savePrefs({ quiet_from: e.target.value })} />
|
||||
<span>–</span>
|
||||
<input type="time" value={data.quiet_to} disabled={!data.quiet} onChange={(e) => e.target.value && void savePrefs({ quiet_to: e.target.value })} />
|
||||
<span className="hint">{t("telegram.serverTime", { time: data.server_time })}{data.quiet_now ? ` · ${t("telegram.quietNow")}` : ""}</span>
|
||||
</div>
|
||||
<div className="hint" style={{ marginTop: 6 }}>{t("telegram.quietHint")}</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -539,6 +539,12 @@ export const de: Messages = {
|
||||
"telegram.intro": "CodeCraft über Telegram mit deinem eigenen Bot nutzen: Nachrichten gehen an deine aktuelle Sitzung, Befehle wechseln Sitzungen, Modi und Modelle, Freigaben und Rückfragen kommen mit Knöpfen. Nur dein Telegram-Konto kann den Bot nutzen.",
|
||||
"telegram.step1": "In Telegram @BotFather öffnen, /newbot senden und den Schritten folgen.",
|
||||
"telegram.step2": "Das Token von BotFather hier einfügen.",
|
||||
"telegram.notify": "Benachrichtigungen",
|
||||
"telegram.factoryAlerts": "Factory: Nachricht, wenn ein Issue eine Frage hat oder fehlschlägt",
|
||||
"telegram.quiet": "Nachtmodus: keine ungefragten Nachrichten",
|
||||
"telegram.serverTime": "Serverzeit {time}",
|
||||
"telegram.quietNow": "gerade ruhig",
|
||||
"telegram.quietHint": "Im Nachtmodus wird nichts von sich aus gesendet: keine Factory-Meldungen, keine Freigaben oder Fragen aus anderen Chats. Der Chat, in dem du gerade per Telegram schreibst, antwortet weiter. Zurückgehaltene Nachrichten werden nicht nachgeholt – sie bleiben in der Weboberfläche sichtbar.",
|
||||
"telegram.connect": "Verbinden",
|
||||
"telegram.checking": "Prüfe…",
|
||||
"telegram.running": "läuft",
|
||||
@@ -1294,6 +1300,9 @@ export const de: Messages = {
|
||||
"factory.closeTitle": "Issue schließen",
|
||||
"factory.closeMsg": "Kommentar zum Schließen von Issue #{n}. Er wird im Issue veröffentlicht, danach wird das Issue geschlossen.",
|
||||
"factory.closeDefault": "Erledigt und abgenommen.",
|
||||
"factory.remove": "Vom Board entfernen",
|
||||
"factory.removeHint": "Nimmt das Issue vom Factory-Board; das Issue im Forge bleibt unberührt. Gelöschte Issues verschwinden von selbst.",
|
||||
"factory.removeConfirm": "#{n} vom Factory-Board entfernen? Das Issue im Forge bleibt unverändert.",
|
||||
"factory.closed": "Issue geschlossen",
|
||||
"factory.skills": "Skills",
|
||||
"factory.skillAdd": "Skill hinzufügen…",
|
||||
|
||||
@@ -538,6 +538,12 @@ export const en = {
|
||||
"telegram.intro": "Use CodeCraft from Telegram with your own bot: messages go to your current session, commands switch sessions, modes and models, approvals and questions come with buttons. Only your Telegram account can use the bot.",
|
||||
"telegram.step1": "In Telegram, open @BotFather, send /newbot and follow the steps.",
|
||||
"telegram.step2": "Paste the token BotFather gives you here.",
|
||||
"telegram.notify": "Notifications",
|
||||
"telegram.factoryAlerts": "Factory: message when an issue gets a question or fails",
|
||||
"telegram.quiet": "Night mode: no unsolicited messages",
|
||||
"telegram.serverTime": "Server time {time}",
|
||||
"telegram.quietNow": "quiet right now",
|
||||
"telegram.quietHint": "During the night mode nothing is sent on your own initiative: no factory alerts, no approvals or questions from other chats. The chat you are talking to in Telegram keeps answering. Messages that are held back are not sent later – they stay visible in the web interface.",
|
||||
"telegram.connect": "Connect",
|
||||
"telegram.checking": "Checking…",
|
||||
"telegram.running": "running",
|
||||
@@ -1293,6 +1299,9 @@ export const en = {
|
||||
"factory.closeTitle": "Close issue",
|
||||
"factory.closeMsg": "Comment for closing issue #{n}. It is posted on the issue, then the issue is closed.",
|
||||
"factory.closeDefault": "Done and accepted.",
|
||||
"factory.remove": "Remove from board",
|
||||
"factory.removeHint": "Take the issue off the factory board; the issue on the forge is not touched. Deleted issues disappear by themselves.",
|
||||
"factory.removeConfirm": "Remove #{n} from the factory board? The issue on the forge stays as it is.",
|
||||
"factory.closed": "Issue closed",
|
||||
"factory.skills": "Skills",
|
||||
"factory.skillAdd": "Add skill…",
|
||||
|
||||
@@ -3,6 +3,18 @@
|
||||
* under "unreleased"; scripts/release.sh renames the key to the release version.
|
||||
*/
|
||||
export const WHATS_NEW: Record<string, { en: string[]; de: string[] }> = {
|
||||
"202611-00065": {
|
||||
en: ["Terminal client now also for Linux riscv64"],
|
||||
de: ["Terminal-Client jetzt auch für Linux riscv64"],
|
||||
},
|
||||
"202611-00064": {
|
||||
en: ["Factory: Telegram message when an issue gets a question or fails (can be switched off)", "Telegram: night mode (22:00–06:00, adjustable) without unsolicited messages"],
|
||||
de: ["Factory: Telegram-Nachricht, wenn ein Issue eine Frage hat oder fehlschlägt (abschaltbar)", "Telegram: Nachtmodus (22:00–06:00, einstellbar) ohne ungefragte Nachrichten"],
|
||||
},
|
||||
"202611-00062": {
|
||||
en: ["Factory: the parallel limit per project is now respected exactly", "Factory: remove issues from the board; issues deleted on the forge disappear by themselves"],
|
||||
de: ["Factory: das Parallel-Limit pro Projekt wird jetzt genau eingehalten", "Factory: Issues vom Board entfernen; im Forge gelöschte Issues verschwinden von selbst"],
|
||||
},
|
||||
"202611-00061": {
|
||||
en: ["Factory: projects are chosen from a dropdown (all projects or a single one)"],
|
||||
de: ["Factory: Projekte werden per Dropdown gewählt (alle oder nur eins)"],
|
||||
|
||||
Reference in new issue
Block a user