From 3849354dbd6c0e03ffca1ba039132b5048807100 Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 25 Nov 2026 22:42:29 +0100 Subject: [PATCH 1/3] automation: a refused agent token file is not retried every 5 s (photocraft#17006) On Windows the token file check starts whoami and PowerShell, about 300 ms on the UI thread. A token file that is open to others (or can't be read) failed that check and was retried every RETRY, forever, so the app froze for ~300 ms every ~5 s while agents were switched on. - A TokenFile problem schedules no retry: it lasts until someone changes the file. Changing the settings tries again. - Retries of a taken port reuse the token the failed start already checked, so they only bind again; a start that succeeded reads the file afresh next time. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/agents/link.rs | 27 ++++++++++++--- crates/automation/tests/it/agents.rs | 50 ++++++++++++++++++++++++++++ 2 files changed, 73 insertions(+), 4 deletions(-) diff --git a/crates/automation/src/agents/link.rs b/crates/automation/src/agents/link.rs index 6296beea7..f37920451 100644 --- a/crates/automation/src/agents/link.rs +++ b/crates/automation/src/agents/link.rs @@ -16,7 +16,7 @@ use crate::security; use crate::server::{self, Listening}; /// How long after a failed start [`AgentLink::sync`] tries again with the same settings, so -/// freeing a taken port is enough. +/// freeing a taken port is enough. A refused token file is not tried again: see [`AgentLink::sync`]. pub const RETRY: Duration = Duration::from_secs(5); /// Why agents cannot connect, or what the app could not apply. `Display` is the English sentence @@ -123,6 +123,10 @@ pub struct AgentLink { applied: Option>, retry_at: Option, retry: Duration, + /// The token a failed start already read and checked, for its retries; cleared once a start + /// succeeds. On Windows the check starts `whoami` and PowerShell (`owner_only`), about 300 ms + /// on the UI thread, which every retry of a taken port would otherwise pay again. + checked_token: Option, status: AgentLinkStatus, } @@ -144,6 +148,7 @@ impl AgentLink { applied: None, retry_at: None, retry: RETRY, + checked_token: None, status: AgentLinkStatus::default(), } } @@ -166,7 +171,11 @@ impl AgentLink { /// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it /// on another port, stop it, or keep it while other settings change. Does nothing while `want` - /// equals the last call's and no retry of a failed start is due. + /// equals the last call's and no retry of a failed start is due. A token file that can't be + /// read or is open to others schedules no retry: that lasts until someone changes the file, + /// and on Windows each check blocks the UI thread for about 300 ms (`owner_only` starts + /// `whoami` and PowerShell), which a retry every [`RETRY`] turned into a stall every few + /// seconds (photocraft#17006). Changing the settings tries again. pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate { let mut update = LinkUpdate::default(); if self.launch.is_some() { @@ -218,6 +227,10 @@ impl AgentLink { update.requests = Some(requests); Ok(()) } + Err(problem @ LinkProblem::TokenFile(_)) => { + log::warn!("{problem}"); + Err(problem) + } Err(problem) => { log::warn!("{problem}"); self.retry_at = Some(motion::now() + self.retry); @@ -229,13 +242,19 @@ impl AgentLink { /// The token from the settings folder (created `0600` when missing), the server, then the /// connection file. Any failure leaves nothing running. - fn start(&self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { + /// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]). + fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { let token_file = dir.join(TOKEN_FILE); - let token = security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?; + let token = match self.checked_token.clone() { + Some(token) => token, + None => security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?, + }; + self.checked_token = Some(token.clone()); let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?; let running = Running { server, dir: dir.to_path_buf(), port_pref }; let connection = Connection::new(running.server.addr.port(), token_file, self.app.clone()); write_connection(dir, &connection).map_err(|e| LinkProblem::Publish(e.to_string()))?; + self.checked_token = None; Ok((running, requests)) } diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index 7ca7bb5f0..cbbbae511 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -308,6 +308,56 @@ fn a_token_file_that_cannot_be_written_keeps_agents_out() { TcpListener::bind(("127.0.0.1", port)).expect("the port was let go"); } +/// A refused token file is not tried again with the same settings: a retry can't succeed until someone changes the +/// file, and on Windows each check starts `whoami` and PowerShell on the UI thread, about 300 ms, which a retry every +/// few seconds turned into a stall that often (photocraft#17006). Changing the settings tries again. +#[trial] +fn a_refused_token_file_is_not_retried_until_the_settings_change() { + let dir = temp_dir("link-token-no-retry"); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let wanted = free_port(); + assert!(link.sync(Some(&on(u32::from(wanted))), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + // The file is fixed, but the same settings don't look at it again. + std::fs::remove_dir(dir.path().join(TOKEN_FILE)).unwrap(); + let same = link.sync(Some(&on(u32::from(wanted))), &host); + assert!(same.requests.is_none() && !same.changed, "no retry with the same settings"); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); + + let changed = link.sync(Some(&on(0)), &host); + assert!(changed.requests.is_some(), "a settings change tries again"); + assert_eq!(link.status().problem, None); +} + +/// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows +/// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time. +#[trial] +fn a_taken_port_retry_reuses_the_checked_token() { + let dir = temp_dir("link-token-reuse"); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x").retry_after(Duration::ZERO); + let taken = TcpListener::bind("127.0.0.1:0").unwrap(); + let port = u32::from(taken.local_addr().unwrap().port()); + assert!(link.sync(Some(&on(port)), &host).requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::Listen { .. })), "{:?}", link.status()); + + // Reading the file now fails, so a retry that read it would report a token file problem. + std::fs::remove_file(dir.path().join(TOKEN_FILE)).unwrap(); + std::fs::create_dir(dir.path().join(TOKEN_FILE)).unwrap(); + drop(taken); + let retried = link.sync(Some(&on(port)), &host); + assert!(retried.requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + + // Once a start succeeded, the next one reads the file again. + let moved = link.sync(Some(&on(0)), &host); + assert!(moved.requests.is_none()); + assert!(matches!(link.status().problem, Some(LinkProblem::TokenFile(_))), "{:?}", link.status()); +} + /// Dropping the link stops its server and removes its connection file. #[trial] fn dropping_the_link_removes_its_connection_file() { From e92a3ffc1bf622c5c1459900512f4314787a675b Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 25 Nov 2026 23:08:43 +0100 Subject: [PATCH 2/3] automation: the agent link replaces a token file the check refuses (photocraft#17006) An older PhotoCraft wrote the agent token file on Windows without restricting it, so it kept its folder's access list (SYSTEM, Administrators, the user). The current check refuses such a file and the link only ever read it, so agents could never connect until someone deleted the file by hand. The link's token file is its own and the token is only its secret: a regular file the check refuses (open to others, a damaged token) is now replaced with a new token, once. A folder or link in its place is still reported and left alone. A token file passed with --control-token-file is unchanged: server_token itself still never replaces a file. Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/agents/link.rs | 34 +++++++++++++++++++++++----- crates/automation/tests/it/agents.rs | 18 +++++++++++++++ 2 files changed, 46 insertions(+), 6 deletions(-) diff --git a/crates/automation/src/agents/link.rs b/crates/automation/src/agents/link.rs index f37920451..18773978a 100644 --- a/crates/automation/src/agents/link.rs +++ b/crates/automation/src/agents/link.rs @@ -171,11 +171,12 @@ impl AgentLink { /// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it /// on another port, stop it, or keep it while other settings change. Does nothing while `want` - /// equals the last call's and no retry of a failed start is due. A token file that can't be - /// read or is open to others schedules no retry: that lasts until someone changes the file, - /// and on Windows each check blocks the UI thread for about 300 ms (`owner_only` starts - /// `whoami` and PowerShell), which a retry every [`RETRY`] turned into a stall every few - /// seconds (photocraft#17006). Changing the settings tries again. + /// equals the last call's and no retry of a failed start is due. A token file refused as it is + /// (open to others, a damaged token) is replaced by a new one ([`Self::start`]). One that still + /// can't be used (a folder in its place, a folder that can't be written) schedules no retry: + /// that lasts until someone changes it, and on Windows each check blocks the UI thread for + /// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`] + /// turned into a stall every few seconds (photocraft#17006). Changing the settings tries again. pub fn sync(&mut self, want: Option<&AgentSettings>, host: &WindowHost) -> LinkUpdate { let mut update = LinkUpdate::default(); if self.launch.is_some() { @@ -243,11 +244,13 @@ impl AgentLink { /// The token from the settings folder (created `0600` when missing), the server, then the /// connection file. Any failure leaves nothing running. /// A retry of a failed start reuses the token that start checked ([`Self::checked_token`]). + /// The token file is the link's own, so one refused as it is gets a new token (see + /// [`fresh_token`]). fn start(&mut self, dir: &Path, port: u16, port_pref: u32, host: &WindowHost) -> Result<(Running, Receiver), LinkProblem> { let token_file = dir.join(TOKEN_FILE); let token = match self.checked_token.clone() { Some(token) => token, - None => security::server_token(None, Some(&token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string()))?, + None => fresh_token(&token_file)?, }; self.checked_token = Some(token.clone()); let (requests, server) = server::listen(port, token, host.clone()).map_err(|e| LinkProblem::Listen { port, error: e.to_string() })?; @@ -269,3 +272,22 @@ impl AgentLink { self.status.problem = Some(problem); } } + +/// The token in `token_file`, created when missing. A regular file the check refuses (one an +/// older app wrote with its folder's access list on Windows, open to Administrators, or a damaged +/// token) is replaced with a new token, once: the token is only this link's secret, and a client +/// reads the new one from the file. Kept, its refusal would keep agents out until someone deleted +/// the file. Anything else in the way (a folder, a link) is reported, not removed. +fn fresh_token(token_file: &Path) -> Result { + let read = || security::server_token(None, Some(token_file)).map_err(|e| LinkProblem::TokenFile(e.to_string())); + let problem = match read() { + Ok(token) => return Ok(token), + Err(problem) => problem, + }; + if !std::fs::symlink_metadata(token_file).is_ok_and(|meta| meta.is_file()) { + return Err(problem); + } + log::warn!("{problem}; writing a new token file"); + std::fs::remove_file(token_file).map_err(|e| LinkProblem::TokenFile(format!("{}: {e}", token_file.display())))?; + read() +} diff --git a/crates/automation/tests/it/agents.rs b/crates/automation/tests/it/agents.rs index cbbbae511..81b2fe5bc 100644 --- a/crates/automation/tests/it/agents.rs +++ b/crates/automation/tests/it/agents.rs @@ -332,6 +332,24 @@ fn a_refused_token_file_is_not_retried_until_the_settings_change() { assert_eq!(link.status().problem, None); } +/// A token file the check refuses as it is (here a damaged token; on Windows also one an older app wrote with its +/// folder's access list, open to Administrators) is the link's own: it is replaced with a new token, so agents can +/// connect instead of staying out until someone deletes the file (photocraft#17006). +#[trial] +fn a_refused_token_file_is_replaced_with_a_new_token() { + let dir = temp_dir("link-token-refresh"); + let file = dir.path().join(TOKEN_FILE); + std::fs::write(&file, "not a token\n").unwrap(); + let host = host(); + let mut link = AgentLink::new(Some(dir.path().to_path_buf()), "x"); + assert!(link.sync(Some(&on(0)), &host).requests.is_some(), "{:?}", link.status()); + assert_eq!(link.status().problem, None); + let token = std::fs::read_to_string(&file).unwrap(); + assert_ne!(token.trim(), "not a token"); + assert_eq!(token.trim().len(), 64, "a new token: {token:?}"); + assert_eq!(read_connection(dir.path()).unwrap().expect("published").port, link.status().port.expect("listening")); +} + /// A retry of a taken port reuses the token its first try checked instead of reading the token file again (on Windows /// that check is about 300 ms on the UI thread, photocraft#17006); a start that succeeded reads it afresh next time. #[trial] From c3f67565941613eabc5c719597397ff6f8d4cfac Mon Sep 17 00:00:00 2001 From: David Mann Date: Wed, 25 Nov 2026 23:30:21 +0100 Subject: [PATCH 3/3] automation: sync's docs name fresh_token as code, not a link to a private item Co-Authored-By: Claude Opus 5.5 --- crates/automation/src/agents/link.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/automation/src/agents/link.rs b/crates/automation/src/agents/link.rs index 18773978a..f43e37f78 100644 --- a/crates/automation/src/agents/link.rs +++ b/crates/automation/src/agents/link.rs @@ -172,7 +172,7 @@ impl AgentLink { /// Brings the server in line with `want` (`None`: agents may not connect): start it, restart it /// on another port, stop it, or keep it while other settings change. Does nothing while `want` /// equals the last call's and no retry of a failed start is due. A token file refused as it is - /// (open to others, a damaged token) is replaced by a new one ([`Self::start`]). One that still + /// (open to others, a damaged token) is replaced by a new one (`fresh_token`). One that still /// can't be used (a folder in its place, a folder that can't be written) schedules no retry: /// that lasts until someone changes it, and on Windows each check blocks the UI thread for /// about 300 ms (`owner_only` starts `whoami` and PowerShell), which a retry every [`RETRY`]