diff --git a/CHANGELOG.md b/CHANGELOG.md index 319fb3e..2b1e12f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,11 +3,12 @@ All notable changes to CodeCraft. Versions follow [Semantic Versioning](https://semver.org/); until 1.0, minor versions may contain breaking changes. -## [v202611-00063] – 2026-11-19 +## [Unreleased] ### 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. +- **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 diff --git a/server/src/api.rs b/server/src/api.rs index 7a9b4ea..b18ece9 100644 --- a/server/src/api.rs +++ b/server/src/api.rs @@ -191,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)) @@ -435,12 +436,52 @@ async fn get_telegram(Extension(user): Extension, State(app): State, + quiet: Option, + quiet_from: Option, + quiet_to: Option, +} + +/// Notification preferences: factory alerts on/off and the night mode. +async fn put_telegram_prefs(Extension(user): Extension, State(app): State, Json(b): Json) -> 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, @@ -451,7 +492,9 @@ async fn put_telegram(Extension(user): Extension, State(app): State, + /// 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 { + 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 { @@ -264,6 +306,9 @@ fn user(app: &App, user_id: &str) -> Result { 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:#}"); } @@ -884,6 +929,10 @@ async fn listen(app: Arc) { 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 { .. }) { @@ -1213,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); + } +} diff --git a/web/src/components/settings/Telegram.tsx b/web/src/components/settings/Telegram.tsx index 5439d4a..b438f36 100644 --- a/web/src/components/settings/Telegram.tsx +++ b/web/src/components/settings/Telegram.tsx @@ -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>) => { + 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 &&
{data.error}
} {data.paired &&
{t("telegram.commands")}
} +

{t("telegram.notify")}

+ + +
+ e.target.value && void savePrefs({ quiet_from: e.target.value })} /> + – + e.target.value && void savePrefs({ quiet_to: e.target.value })} /> + {t("telegram.serverTime", { time: data.server_time })}{data.quiet_now ? ` · ${t("telegram.quietNow")}` : ""} +
+
{t("telegram.quietHint")}
)} diff --git a/web/src/i18n/de.ts b/web/src/i18n/de.ts index 4cbf9ce..c181723 100644 --- a/web/src/i18n/de.ts +++ b/web/src/i18n/de.ts @@ -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", diff --git a/web/src/i18n/en.ts b/web/src/i18n/en.ts index d1fbfc2..17dde3e 100644 --- a/web/src/i18n/en.ts +++ b/web/src/i18n/en.ts @@ -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", diff --git a/web/src/whatsnew.ts b/web/src/whatsnew.ts index 426413b..1d4baea 100644 --- a/web/src/whatsnew.ts +++ b/web/src/whatsnew.ts @@ -3,9 +3,9 @@ * under "unreleased"; scripts/release.sh renames the key to the release version. */ export const WHATS_NEW: Record = { - "202611-00063": { - en: ["Factory: Telegram message when an issue gets a question or fails"], - de: ["Factory: Telegram-Nachricht, wenn ein Issue eine Frage hat oder fehlschlägt"], + unreleased: { + 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"],