From d4bd4acfe95eae53a19e557c903b6c4103ed3c44 Mon Sep 17 00:00:00 2001 From: javis-bot Date: Thu, 12 Nov 2026 19:49:47 +0900 Subject: [PATCH] fix(app): channel sync keeps a new channel's empty fields out on retry, orders saves, drops stale lookups - A rate-limited edit of a newly registered channel is retried with the same "never clear Discord with an empty field" rule (it was retried as an existing channel and cleared the topic). - Channel edits go one at a time, and Discord's form of the name is written back only while the settings still hold the name that was sent, so a slow answer to an earlier save never overwrites a later one. - The chat channel screen drops a Discord name/topic lookup that answers after the ID was changed. Co-Authored-By: Claude Opus 5.5 --- app/src/admin.spec.md | 13 ++++--- app/src/channel_sync.rs | 83 +++++++++++++++++++++++++++++++++-------- app/ui/app.js | 6 ++- 3 files changed, 80 insertions(+), 22 deletions(-) diff --git a/app/src/admin.spec.md b/app/src/admin.spec.md index 6ab0014..95fefd5 100644 --- a/app/src/admin.spec.md +++ b/app/src/admin.spec.md @@ -215,12 +215,14 @@ start it first, so nothing answers before the brain can, and stop it last. keeps its Discord name and topic in step with its `name` and `description`: - Registering a channel fills empty name and description with the channel's Discord name and topic - (`discord_channel_info`). + (`discord_channel_info`); an answer that arrives after the ID was changed is dropped. - `settings_apply` with `chatChannels` first refuses a description over Discord's topic limit (1,024 characters) of a syncing channel, saving nothing. After saving, each syncing channel that is new, or whose name or description changed, is compared with Discord and edited where they - differ (a new channel never clears a Discord name or topic with an empty field). Discord's form of - the name (spaces become `-`) is written back to the settings so the screen shows it. The results + differ (a new channel never clears a Discord name or topic with an empty field, also when its edit + is retried later). Edits go one at a time, so a later save waits for an earlier one and Discord + ends with the later. Discord's form of the name (spaces become `-`) is written back to the + settings so the screen shows it, only while the settings still hold the name that was sent. The results come back in `sync` (`applied` with the name, `pending` with the wait, `failed` with the reason) and stay readable with `channel_sync_status`. - Discord allows about two name or topic edits per channel in ten minutes. A refused edit is @@ -327,8 +329,9 @@ UTF-8 read on to the end; the window data folder (data folder, or a scratch fold the TTS speed reaching the worker's arguments; chat channel names and topics (only new or edited syncing channels sent, the topic limit refused before saving, Discord's form of the name written back, a missing permission failing with the reason and the text kept, a rate-limited edit pending -and retried once with the latest text, a new channel never clearing Discord, unchanged ones not -edited; through `settings_apply` too); a background start that is starting at once, so a stop right after it cancels it +and retried once with the latest text, a new channel never clearing Discord (also on its retry), a +slow first save never overwriting a later one, unchanged ones not edited; through `settings_apply` +too); a background start that is starting at once, so a stop right after it cancels it and a second start is refused, also through the admin commands; a failed stop reported as failed; the brain's config loaded without writing to the home folder, `tests/test_config_db_path.py`); the dashboard from made-up events (captions replaced and cleared, latency stages and medians, an answer matched to its asker's final, missed requests without text); the admin diff --git a/app/src/channel_sync.rs b/app/src/channel_sync.rs index 6e7a411..19dd438 100644 --- a/app/src/channel_sync.rs +++ b/app/src/channel_sync.rs @@ -72,13 +72,18 @@ pub struct Syncer { api: Arc, settings_file: PathBuf, status: Mutex>, - /// Channels with a retry already waiting (another save while waiting adds none). - retrying: Mutex>, + /// Channels with a retry already waiting (another save while waiting adds none), and whether + /// that channel was new (so the retry still keeps empty fields out). + retrying: Mutex>, + /// One channel edit at a time: a later save waits for an earlier one, so a slow answer to the + /// earlier never lands after the later. + edit_lock: tokio::sync::Mutex<()>, } impl Syncer { pub fn new(api: Arc, settings_file: PathBuf) -> Arc { - Arc::new(Self { api, settings_file, status: Mutex::default(), retrying: Mutex::default() }) + Arc::new(Self { api, settings_file, status: Mutex::default(), retrying: Mutex::default(), + edit_lock: tokio::sync::Mutex::new(()) }) } /// A channel's name and topic on Discord now (the screens fill a newly registered channel with them). @@ -108,9 +113,10 @@ impl Syncer { } async fn sync_one(self: &Arc, c: &ChatChannelSettings, is_new: bool) -> SyncState { + let _one_at_a_time = self.edit_lock.lock().await; let current = match self.api.info(c.id).await { Ok(i) => i, - Err(e) => return self.refused(c.id, e), + Err(e) => return self.refused(c.id, e, is_new), }; let keep = |v: &str| !(is_new && v.trim().is_empty()); let name = (keep(&c.name) && c.name != current.name).then_some(c.name.as_str()); @@ -121,25 +127,31 @@ impl Syncer { match self.api.edit(c.id, name, topic).await { Ok(stored) => { if keep(&c.name) && stored.name != c.name { - self.write_name(c.id, &stored.name); + self.write_name(c.id, &c.name, &stored.name); } crate::info_log!("chat", "channel {} name and topic updated on Discord", c.id); SyncState::Applied { name: stored.name } } - Err(e) => self.refused(c.id, e), + Err(e) => self.refused(c.id, e, is_new), } } - fn refused(self: &Arc, id: u64, e: ApiError) -> SyncState { + fn refused(self: &Arc, id: u64, e: ApiError, is_new: bool) -> SyncState { match e { ApiError::RateLimited(wait) => { crate::info_log!("chat", "channel {id}: Discord asks to wait {}s before the next edit", wait.as_secs()); - if self.retrying.lock().unwrap().insert(id) { + let first = { + let mut r = self.retrying.lock().unwrap(); + let first = !r.contains_key(&id); + *r.entry(id).or_insert(is_new) |= is_new; + first + }; + if first { let me = self.clone(); tokio::spawn(async move { tokio::time::sleep(wait).await; - me.retrying.lock().unwrap().remove(&id); - me.retry(id).await; + let is_new = me.retrying.lock().unwrap().remove(&id).unwrap_or(false); + me.retry(id, is_new).await; }); } SyncState::Pending { retry_in_sec: wait.as_secs().max(1) } @@ -152,11 +164,11 @@ impl Syncer { } /// Try a pending channel again with what the settings hold now. - async fn retry(self: &Arc, id: u64) { + async fn retry(self: &Arc, id: u64, is_new: bool) { let Ok(settings) = crate::settings::load_settings(&self.settings_file) else { return }; match settings.chat_channels.into_iter().find(|c| c.id == id && c.sync_discord) { Some(c) => { - let state = self.sync_one(&c, false).await; + let state = self.sync_one(&c, is_new).await; self.status.lock().unwrap().insert(id, state); } None => { @@ -165,15 +177,21 @@ impl Syncer { } } - /// Show Discord's form of the name (spaces become `-`) in the app too. - fn write_name(&self, id: u64, name: &str) { + /// Show Discord's form of the name (spaces become `-`) in the app too, only while the settings + /// still hold the name that was sent (a later save keeps its own). + fn write_name(&self, id: u64, sent: &str, name: &str) { let Ok(view) = crate::settings_edit::view(&self.settings_file) else { return }; let Some(Value::Array(mut list)) = view.get("chatChannels").cloned() else { return }; + let mut changed = false; for c in &mut list { - if c["id"].as_str() == Some(id.to_string().as_str()) { + if c["id"].as_str() == Some(id.to_string().as_str()) && c["name"].as_str() == Some(sent) { c["name"] = json!(name); + changed = true; } } + if !changed { + return; + } let mut changes = serde_json::Map::new(); changes.insert("chatChannels".into(), Value::Array(list)); if let Err(e) = crate::settings_edit::apply(&self.settings_file, &changes) { @@ -249,6 +267,8 @@ mod tests { forbidden: Vec, limited: Mutex, edits: Mutex, Option)>>, + /// How long each next edit takes (the first save's slow answer). + delays: Mutex>, } #[async_trait] impl ChannelApi for FakeDiscord { @@ -259,6 +279,10 @@ mod tests { if self.forbidden.contains(&id) { return Err(ApiError::Failed("봇에 이 채널의 채널 관리 권한이 없습니다".into())); } + let delay = { let mut d = self.delays.lock().unwrap(); if d.is_empty() { None } else { Some(d.remove(0)) } }; + if let Some(d) = delay { + tokio::time::sleep(d).await; + } { let mut l = self.limited.lock().unwrap(); if *l > 0 { @@ -375,4 +399,33 @@ mod tests { s.sync(vec![ch(B, "잡담", "아무 말")], &[]).await; assert!(d.edits.lock().unwrap().is_empty(), "nothing differs from Discord: no edit"); } + + #[tokio::test] + async fn a_retried_new_channel_still_never_clears_discord_with_an_empty_field() { + let d = fake(vec![], 1); + let file = settings_with(&[ch(B, "잡담 2", "")]); + let s = Syncer::new(d.clone(), file); + let out = s.sync(vec![ch(B, "잡담 2", "")], &[]).await; + assert!(matches!(out[0].1, SyncState::Pending { .. }), "{out:?}"); + tokio::time::sleep(Duration::from_millis(500)).await; + assert_eq!(s.status()[&B], SyncState::Applied { name: "잡담-2".into() }); + assert_eq!(d.channels.lock().unwrap()[&B].topic, "아무 말", "the retry kept the empty description out"); + } + + #[tokio::test] + async fn a_slow_first_save_never_overwrites_a_later_one() { + let d = fake(vec![], 0); + *d.delays.lock().unwrap() = vec![Duration::from_millis(300)]; + let file = settings_with(&[ch(A, "일정 표", "")]); + let s = Syncer::new(d.clone(), file.clone()); + let s1 = s.clone(); + let first = tokio::spawn(async move { s1.sync(vec![ch(A, "일정 표", "")], &[ch(A, "일정", "")]).await }); + tokio::time::sleep(Duration::from_millis(50)).await; + // Saved again while Discord still answers the first edit. + std::fs::write(&file, json!({"chatChannels": [{"id": A.to_string(), "name": "회의", "description": ""}]}).to_string()).unwrap(); + s.sync(vec![ch(A, "회의", "")], &[ch(A, "일정 표", "")]).await; + first.await.unwrap(); + assert_eq!(d.channels.lock().unwrap()[&A].name, "회의", "Discord ends with the later save"); + assert_eq!(crate::settings::load_settings(&file).unwrap().chat_channels[0].name, "회의", "and so does the app"); + } } diff --git a/app/ui/app.js b/app/ui/app.js index 50b555e..a8ab246 100644 --- a/app/ui/app.js +++ b/app/ui/app.js @@ -140,9 +140,11 @@ function chatChannelsEditor(f, value) { const desc = h("input", { type: "text", value: c.description ?? "", placeholder: "무엇에 쓰는 채널인지", "data-k": "description" }); // A newly registered channel starts with its Discord name and topic. id.addEventListener("change", async () => { - if (!id.value.trim() || (name.value && desc.value)) return; + const asked = id.value.trim(); + if (!asked || (name.value && desc.value)) return; try { - const info = await api("discord_channel_info", { id: id.value.trim() }); + const info = await api("discord_channel_info", { id: asked }); + if (id.value.trim() !== asked) return; // the ID changed meanwhile: this answer is for another channel if (!name.value) name.value = info.name; if (!desc.value) desc.value = info.topic; } catch (e) { fail(e); }