feat(app): chat channel name/topic sync, TTS speed, safe window close
Review follow-ups to M5. - Chat channel names and topics (app/src/channel_sync.rs): a channel with syncDiscord (default on) gets its name and description as its Discord name and topic when saved; registering fills them from Discord; Discord's form of the name is written back; a topic over 1,024 characters is refused before saving; a rate-limited edit is pending and retried once by itself with the latest text; a missing permission fails with the reason and the app keeps the text. Commands discord_channel_info and channel_sync_status. Checked on real Discord with a temporary channel (fill, edit, rate limit, automatic retry). - voice.tts.speed (0.5-2.0) on the model screen, passed to the worker as --melo-speed. MeloTTS's Korean model has one voice, so no voice choice. - Closing the window runs AdminApi::shutdown first: an install in progress is cancelled and waited for, the services stop, a failed run's leftovers (Strata) are cleared (Controller::shutdown). If that fails the window stays open with the reason; closing again quits. - WebView2 data goes in the data folder (cache/webview), or a temp scratch folder before one is chosen, removed at the next start: %APPDATA%\JarvisBot holds only the location file. - Command output that is not UTF-8 (CP949 on a PC without the UTF-8 option) is decoded in the OEM code page instead of ending the reading. Verified on the win-ci VM: closing during the install leaves no process, no --location keeps only location.json under %APPDATA%, the unit tests on Windows 168/168. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -21,6 +21,7 @@ pub struct AdminApi {
|
||||
dir: Mutex<Option<DataDir>>,
|
||||
controller: Mutex<Option<Arc<Controller>>>,
|
||||
installer: Mutex<Option<Arc<crate::install::Installer>>>,
|
||||
syncer: Mutex<Option<Arc<crate::channel_sync::Syncer>>>,
|
||||
hub: Arc<LogHub>,
|
||||
}
|
||||
|
||||
@@ -45,7 +46,8 @@ impl AdminApi {
|
||||
/// `location_file`: where the data folder is remembered; `hub`: the app's log hub.
|
||||
pub fn new(location_file: &Path, hub: Arc<LogHub>) -> Self {
|
||||
let dir = DataDir::locate(location_file);
|
||||
Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None), hub }
|
||||
Self { location_file: location_file.to_path_buf(), dir: Mutex::new(dir), controller: Mutex::new(None), installer: Mutex::new(None),
|
||||
syncer: Mutex::new(None), hub }
|
||||
}
|
||||
|
||||
fn dir(&self) -> Result<DataDir, String> {
|
||||
@@ -86,26 +88,40 @@ impl AdminApi {
|
||||
Ok(i.clone().unwrap())
|
||||
}
|
||||
|
||||
/// Keeps chat channel names and topics in step with Discord, with the stored bot token.
|
||||
fn syncer(&self) -> Result<Arc<crate::channel_sync::Syncer>, String> {
|
||||
let dir = self.dir()?;
|
||||
let mut s = self.syncer.lock().unwrap();
|
||||
Ok(s.get_or_insert_with(|| crate::channel_sync::Syncer::new(
|
||||
Arc::new(crate::channel_sync::DiscordRest::new(dir.secrets_file())), dir.settings_file())).clone())
|
||||
}
|
||||
|
||||
fn controller(&self) -> Result<Arc<Controller>, String> {
|
||||
let dir = self.dir()?;
|
||||
let mut c = self.controller.lock().unwrap();
|
||||
Ok(c.get_or_insert_with(|| Controller::new(ServicesHost::new(dir.path().to_path_buf()))).clone())
|
||||
}
|
||||
|
||||
/// Stop the services (and cancel a start) when the app closes, so nothing it started (the
|
||||
/// worker, Strata) keeps running.
|
||||
pub async fn shutdown(&self) {
|
||||
let controller = self.controller.lock().unwrap().clone();
|
||||
if let Some(c) = controller {
|
||||
if matches!(c.state(), State::Running | State::Starting) {
|
||||
let _ = c.stop().await;
|
||||
}
|
||||
// A cancelled start finishes in the background: wait for it (Strata's stop takes up to
|
||||
// two minutes) before the app exits.
|
||||
let until = std::time::Instant::now() + std::time::Duration::from_secs(150);
|
||||
while matches!(c.state(), State::Starting | State::Stopping) && std::time::Instant::now() < until {
|
||||
/// The app is closing: cancel an install in progress and wait for it (its commands and their
|
||||
/// children end), stop the services (a start in progress is cancelled and waited for) and clear
|
||||
/// what a failed run may have left (the LLM's server). An error means something may still run;
|
||||
/// the window then stays open (admin.spec.md, "Window and Windows build").
|
||||
pub async fn shutdown(&self) -> Result<(), String> {
|
||||
let installer = self.installer.lock().unwrap().clone();
|
||||
if let Some(i) = installer.filter(|i| i.running()) {
|
||||
i.cancel();
|
||||
let until = std::time::Instant::now() + std::time::Duration::from_secs(60);
|
||||
while i.running() && std::time::Instant::now() < until {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
}
|
||||
if i.running() {
|
||||
return Err("설치를 멈추지 못했습니다".into());
|
||||
}
|
||||
}
|
||||
let controller = self.controller.lock().unwrap().clone();
|
||||
match controller {
|
||||
Some(c) => c.shutdown().await,
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -207,8 +223,39 @@ impl AdminApi {
|
||||
"settings_apply" => {
|
||||
let changes: Map<String, Value> = arg(&args, "changes")?.as_object().cloned()
|
||||
.ok_or("changes는 객체여야 합니다")?;
|
||||
crate::settings_edit::apply(&self.dir()?.settings_file(), &changes).map_err(|e| e.0)?;
|
||||
Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running}))
|
||||
let file = self.dir()?.settings_file();
|
||||
// Chat channels: a topic Discord would refuse is caught before saving; after saving,
|
||||
// the edited channels go to Discord (admin.spec.md, "Chat channel names and topics").
|
||||
let chats = changes.get("chatChannels");
|
||||
let old = match chats {
|
||||
Some(list) => {
|
||||
let parsed = crate::settings::parse_settings(&json!({"chatChannels": list})).map_err(|e| e.0)?;
|
||||
crate::channel_sync::check_topics(&parsed.chat_channels)?;
|
||||
crate::settings::load_settings(&file).map_err(|e| e.0)?.chat_channels
|
||||
}
|
||||
None => vec![],
|
||||
};
|
||||
crate::settings_edit::apply(&file, &changes).map_err(|e| e.0)?;
|
||||
let mut sync = vec![];
|
||||
if chats.is_some() {
|
||||
let new = crate::settings::load_settings(&file).map_err(|e| e.0)?.chat_channels;
|
||||
let todo = crate::channel_sync::changed(&old, &new);
|
||||
if !todo.is_empty() {
|
||||
for (id, state) in self.syncer()?.sync(todo, &old).await {
|
||||
let mut v = json!(state);
|
||||
v["id"] = json!(id.to_string());
|
||||
sync.push(v);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(json!({"saved": changes.len(), "restartNeeded": self.controller()?.state() == crate::control::State::Running,
|
||||
"sync": sync}))
|
||||
}
|
||||
"channel_sync_status" => Ok(Value::Object(self.syncer()?.status().into_iter()
|
||||
.map(|(id, s)| (id.to_string(), json!(s))).collect())),
|
||||
"discord_channel_info" => {
|
||||
let id: u64 = arg_str(&args, "id")?.trim().parse().map_err(|_| "채널 ID가 올바르지 않습니다")?;
|
||||
Ok(json!(self.syncer()?.info(id).await?))
|
||||
}
|
||||
// Starting can take long (the LLM's first start downloads the model), so it runs in the
|
||||
// background and the dashboard shows how it goes; stop also cancels a start.
|
||||
@@ -258,7 +305,8 @@ mod tests {
|
||||
fn api(tag: &str) -> (AdminApi, PathBuf) {
|
||||
let base = temp_dir(tag);
|
||||
let loc = base.join("cfg").join("location.json");
|
||||
(AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), installer: Mutex::new(None), hub: LogHub::new(None) },
|
||||
(AdminApi { location_file: loc, dir: Mutex::new(None), controller: Mutex::new(None), installer: Mutex::new(None), syncer: Mutex::new(None),
|
||||
hub: LogHub::new(None) },
|
||||
base)
|
||||
}
|
||||
|
||||
@@ -326,13 +374,83 @@ mod tests {
|
||||
#[tokio::test]
|
||||
async fn closing_the_app_while_starting_waits_until_everything_is_stopped() {
|
||||
let (a, base) = api("api5");
|
||||
a.shutdown().await; // nothing chosen or started yet
|
||||
a.shutdown().await.unwrap(); // nothing chosen or started yet
|
||||
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
|
||||
a.call("service_start", json!({})).await.unwrap();
|
||||
a.shutdown().await;
|
||||
a.shutdown().await.unwrap();
|
||||
assert_eq!(a.call("dashboard", json!({})).await.unwrap()["state"], json!("stopped"));
|
||||
}
|
||||
|
||||
/// A step that runs until it is cancelled (an install in progress when the window closes).
|
||||
struct Endless;
|
||||
#[async_trait::async_trait]
|
||||
impl crate::install::Step for Endless {
|
||||
fn id(&self) -> &'static str { "endless" }
|
||||
fn label(&self) -> &'static str { "endless" }
|
||||
fn size_hint(&self) -> &'static str { "" }
|
||||
fn version(&self, _: &crate::install::Layout) -> String { "1".into() }
|
||||
async fn run(&self, ctx: &crate::install::Ctx) -> Result<(), String> {
|
||||
while !ctx.cancel.load(std::sync::atomic::Ordering::SeqCst) {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(20)).await;
|
||||
}
|
||||
Err("cancelled".into())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn closing_the_app_during_the_install_cancels_it_and_waits() {
|
||||
let (a, base) = api("api6");
|
||||
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
|
||||
let layout = crate::install::Layout { data: base.join("d"), src: PathBuf::from("src") };
|
||||
*a.installer.lock().unwrap() = Some(crate::install::Installer::new(layout, vec![Box::new(Endless)]));
|
||||
a.call("install_start", json!({})).await.unwrap();
|
||||
tokio::time::sleep(std::time::Duration::from_millis(100)).await;
|
||||
assert_eq!(a.call("install_status", json!({})).await.unwrap()["running"], json!(true));
|
||||
a.shutdown().await.unwrap();
|
||||
let st = a.call("install_status", json!({})).await.unwrap();
|
||||
assert_eq!((st["running"].clone(), st["steps"][0]["state"].clone()), (json!(false), json!("failed")));
|
||||
}
|
||||
|
||||
/// Discord for the chat channel screen: one channel whose names lose their spaces.
|
||||
struct OneChannel(Mutex<crate::channel_sync::ChannelInfo>);
|
||||
#[async_trait::async_trait]
|
||||
impl crate::channel_sync::ChannelApi for OneChannel {
|
||||
async fn info(&self, _: u64) -> Result<crate::channel_sync::ChannelInfo, crate::channel_sync::ApiError> {
|
||||
Ok(self.0.lock().unwrap().clone())
|
||||
}
|
||||
async fn edit(&self, _: u64, name: Option<&str>, topic: Option<&str>)
|
||||
-> Result<crate::channel_sync::ChannelInfo, crate::channel_sync::ApiError> {
|
||||
let mut c = self.0.lock().unwrap();
|
||||
if let Some(n) = name { c.name = n.replace(' ', "-"); }
|
||||
if let Some(t) = topic { c.topic = t.into(); }
|
||||
Ok(c.clone())
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn saving_chat_channels_brings_their_names_and_topics_to_discord() {
|
||||
let (a, base) = api("api7");
|
||||
a.call("folder_choose", json!({"path": base.join("d").to_string_lossy()})).await.unwrap();
|
||||
let discord = Arc::new(OneChannel(Mutex::new(crate::channel_sync::ChannelInfo { name: "memo".into(), topic: "".into() })));
|
||||
let file = a.dir().unwrap().settings_file();
|
||||
*a.syncer.lock().unwrap() = Some(crate::channel_sync::Syncer::new(discord.clone(), file.clone()));
|
||||
const ID: &str = "100000000000000001";
|
||||
// Registering fills the fields from Discord.
|
||||
assert_eq!(a.call("discord_channel_info", json!({"id": ID})).await.unwrap()["name"], json!("memo"));
|
||||
let r = a.call("settings_apply", json!({"changes": {"chatChannels": [
|
||||
{"id": ID, "name": "할 일 메모", "description": "오늘 할 일"}]}})).await.unwrap();
|
||||
assert_eq!(r["sync"][0], json!({"id": ID, "state": "applied", "name": "할-일-메모"}));
|
||||
assert_eq!(discord.0.lock().unwrap().topic, "오늘 할 일");
|
||||
assert_eq!(a.call("settings_view", json!({})).await.unwrap()["chatChannels"][0]["name"], json!("할-일-메모"));
|
||||
assert_eq!(a.call("channel_sync_status", json!({})).await.unwrap()[ID]["state"], json!("applied"));
|
||||
// A topic over Discord's limit is refused and nothing is saved.
|
||||
let before = std::fs::read_to_string(&file).unwrap();
|
||||
let e = a.call("settings_apply", json!({"changes": {"chatChannels": [
|
||||
{"id": ID, "name": "할-일-메모", "description": "가".repeat(1025)}]}})).await.unwrap_err();
|
||||
assert!(e.contains("1024"), "{e}");
|
||||
assert_eq!(std::fs::read_to_string(&file).unwrap(), before);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_start_is_starting_when_it_answers_so_a_stop_right_after_it_is_not_refused() {
|
||||
let (a, base) = api("api4");
|
||||
|
||||
Reference in New Issue
Block a user