Skip to content

A modern terminal with a built-in multiplexer: close it and your sessions keep running. Run shells and tons of AI agents across your machines, then pick them up from desktop, browser, TUI and more. Written in Rust with no UI framework: interface drawn straight on the GPU. No Electron, GPUI or webview.

fix(import): keep receipts off the mux thread and let failed recovery go

RoversX8c440fca435c
diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rs
index ce9d8839..19d712bc 100644
--- a/wezterm-gui/src/settings_window.rs
+++ b/wezterm-gui/src/settings_window.rs
@@ -5232,6 +5232,7 @@ impl SettingsWindow {
if self.import_busy() { return; }
#[cfg(unix)]
if self.ui.import_source != source {
+ self.ui.session_import.abandon();
self.ui.session_import = session_import::ImportUi::default();
}
self.ui.import_source = source;
diff --git a/wezterm-gui/src/settings_window/import.rs b/wezterm-gui/src/settings_window/import.rs
index a461ad0a..f87c7a73 100644
--- a/wezterm-gui/src/settings_window/import.rs
+++ b/wezterm-gui/src/settings_window/import.rs
@@ -154,6 +154,7 @@ impl SettingsWindow {
self.ui.import_result = None;
#[cfg(unix)]
{
+ self.ui.session_import.abandon();
self.ui.session_import = session_import::ImportUi::default();
}
}
diff --git a/wezterm-gui/src/settings_window/session_import.rs b/wezterm-gui/src/settings_window/session_import.rs
index 26ad0a59..313aa7e8 100644
--- a/wezterm-gui/src/settings_window/session_import.rs
+++ b/wezterm-gui/src/settings_window/session_import.rs
@@ -58,8 +58,17 @@ impl Default for ImportUi {
}
impl ImportUi {
+ /// An import whose outcome is unknown blocks the page until a recovery
+ /// attempt fails. Then the user may leave it behind (see `abandon`).
pub(super) fn busy(&self) -> bool {
- self.busy || self.pending.is_some()
+ self.busy || (self.pending.is_some() && !self.failed)
+ }
+
+ /// Stop tracking an import whose outcome could not be found out. Its
+ /// receipt on the owner still keeps that request from running twice.
+ pub(super) fn abandon(&mut self) {
+ self.pending = None;
+ UNRESOLVED.with(|slot| slot.borrow_mut().take());
}
pub(super) fn has_preview(&self) -> bool {
@@ -183,7 +192,7 @@ impl ImportTarget {
.get_import_session_status(request.request_id.clone())
.await?
} else {
- session_import::status(&request.request_id)?
+ session_import::status(request.request_id.clone()).await?
};
match status {
codec::ImportSessionStatus::NotFound => self
@@ -399,7 +408,10 @@ impl SettingsWindow {
if self.ui.session_import.pending.is_some()
&& !matches!(action, SettingsAction::SessionImportRecover)
{
- return;
+ if self.ui.session_import.busy() {
+ return;
+ }
+ self.ui.session_import.abandon();
}
let selected_source = self.ui.import_source;
let Ok(provider) = selected_source.provider() else {
@@ -1232,6 +1244,28 @@ impl SettingsWindow {
mod tests {
use super::*;
+ #[test]
+ fn a_failed_recovery_can_be_left_behind() {
+ let mut state = ImportUi::default();
+ state.pending = Some(codec::ImportSessionRequest {
+ request_id: "1-example".into(),
+ request: thinkterm_import::ImportRequest {
+ source: "example".into(),
+ session: "development".into(),
+ mode: ImportMode::Layout,
+ fingerprint: "example-fingerprint".into(),
+ space_name: "Imported".into(),
+ },
+ });
+ assert!(state.busy());
+ state.failed = true;
+ assert!(!state.busy());
+ UNRESOLVED.with(|slot| *slot.borrow_mut() = Some(state.clone()));
+ state.abandon();
+ assert!(state.pending.is_none());
+ assert!(ImportUi::default().pending.is_none());
+ }
+
#[test]
fn import_follows_the_space_owner_and_never_falls_back_for_a_missing_space() {
let store: crate::workspace_threads::WorkspaceThreadStore = serde_json::from_value(serde_json::json!({
diff --git a/wezterm-mux-server-impl/src/session_import/mod.rs b/wezterm-mux-server-impl/src/session_import/mod.rs
index 88d38a0b..ca719e41 100644
--- a/wezterm-mux-server-impl/src/session_import/mod.rs
+++ b/wezterm-mux-server-impl/src/session_import/mod.rs
@@ -244,8 +244,9 @@ fn make_tree(plan: &ImportPlan, name: &str) -> ThinkTermTree {
tree
}
-pub fn status(request_id: &str) -> Result<codec::ImportSessionStatus> {
- receipt::Store::owner().status(request_id)
+/// Receipts take a file lock, so the lookup runs on a blocking thread.
+pub async fn status(request_id: String) -> Result<codec::ImportSessionStatus> {
+ smol::unblock(move || receipt::Store::owner().status(&request_id)).await
}
/// The owner persists the new rows and their layouts before committing the
@@ -256,14 +257,18 @@ where
F: FnMut(&ThinkTermTree, bool, &[ImportedThreadLayout]) -> Result<()>,
{
let _import = IMPORT.lock().await;
- let attempt = match receipt::Store::owner().start(request.clone())? {
+ let started = {
+ let request = request.clone();
+ smol::unblock(move || receipt::Store::owner().start(request)).await?
+ };
+ let attempt = match started {
receipt::Started::Completed(result) => return Ok(result),
receipt::Started::New(attempt) => attempt,
};
let result = execute_new(request.request, persist, &attempt).await;
match result {
Ok(result) => {
- attempt.complete().context(
+ attempt.complete().await.context(
"Save completed import receipt; query the import result before retrying",
)?;
Ok(result)
@@ -271,6 +276,7 @@ where
Err(err) => {
attempt
.fail(&format!("{err:#}"))
+ .await
.context("Save failed import receipt; query the import result before retrying")?;
Err(err)
}
@@ -313,6 +319,7 @@ where
};
attempt
.destination(response.clone())
+ .await
.context("Save import destination before handoff")?;
let mut panes: HashMap<u32, Arc<dyn Pane>> = HashMap::new();
diff --git a/wezterm-mux-server-impl/src/session_import/receipt.rs b/wezterm-mux-server-impl/src/session_import/receipt.rs
index 39d03098..42a49da7 100644
--- a/wezterm-mux-server-impl/src/session_import/receipt.rs
+++ b/wezterm-mux-server-impl/src/session_import/receipt.rs
@@ -65,10 +65,9 @@ fn issued_at(id: &str) -> Result<u64> {
&& timestamp.to_string() == time,
"Invalid import request ID"
);
- ensure!(
- timestamp <= now().saturating_add(300),
- "Import request time is in the future; check the clocks on both machines"
- );
+ // The time comes from the client's clock. A server whose clock is behind
+ // (a small board without NTP) still accepts it; the receipt starts to
+ // age once this clock passes that time.
Ok(timestamp)
}
@@ -194,11 +193,11 @@ impl Store {
}
}
-impl Attempt {
- pub(super) fn destination(&self, result: ImportSessionResponse) -> Result<()> {
- self.store.locked(|records| {
+impl Store {
+ fn set_destination(&self, id: &str, result: ImportSessionResponse) -> Result<()> {
+ self.locked(|records| {
records
- .get_mut(&self.request_id)
+ .get_mut(id)
.context("Import receipt is missing")?
.destination = Some(result);
// Check the full result before touching the session and leave room
@@ -211,22 +210,43 @@ impl Attempt {
})
}
- pub(super) fn complete(&self) -> Result<()> {
- self.update(|receipt| receipt.outcome = Outcome::Completed)
+ fn set_outcome(&self, id: &str, outcome: Outcome) -> Result<()> {
+ self.locked(|records| {
+ records
+ .get_mut(id)
+ .context("Import receipt is missing")?
+ .outcome = outcome;
+ Ok(((), true))
+ })
+ }
+}
+
+impl Attempt {
+ pub(super) async fn destination(&self, result: ImportSessionResponse) -> Result<()> {
+ self.write(move |store, id| store.set_destination(id, result))
+ .await
}
- pub(super) fn fail(&self, error: &str) -> Result<()> {
- self.update(|receipt| receipt.outcome = Outcome::Failed(error.chars().take(1024).collect()))
+ pub(super) async fn complete(&self) -> Result<()> {
+ self.write(|store, id| store.set_outcome(id, Outcome::Completed))
+ .await
}
- fn update(&self, change: impl FnOnce(&mut Receipt)) -> Result<()> {
- self.store.locked(|records| {
- let receipt = records
- .get_mut(&self.request_id)
- .context("Import receipt is missing")?;
- change(receipt);
- Ok(((), true))
- })
+ pub(super) async fn fail(&self, error: &str) -> Result<()> {
+ let outcome = Outcome::Failed(error.chars().take(1024).collect());
+ self.write(move |store, id| store.set_outcome(id, outcome))
+ .await
+ }
+
+ /// Receipt writes lock a file and wait for the disk. They run on a
+ /// blocking thread so the thread that serves terminals never waits.
+ async fn write(
+ &self,
+ write: impl FnOnce(&Store, &str) -> Result<()> + Send + 'static,
+ ) -> Result<()> {
+ let store = self.store.clone();
+ let id = self.request_id.clone();
+ smol::unblock(move || write(&store, &id)).await
}
}
@@ -289,8 +309,8 @@ mod tests {
store.status(&request.request_id).unwrap(),
ImportSessionStatus::Running
);
- attempt.destination(destination()).unwrap();
- attempt.complete().unwrap();
+ smol::block_on(attempt.destination(destination())).unwrap();
+ smol::block_on(attempt.complete()).unwrap();
drop(attempt);
let reloaded = Store {
path: store.path.clone(),
@@ -315,7 +335,7 @@ mod tests {
};
let interrupted = request(now());
let attempt = begin(&store, interrupted.clone());
- attempt.destination(destination()).unwrap();
+ smol::block_on(attempt.destination(destination())).unwrap();
drop(attempt);
assert_eq!(
store.status(&interrupted.request_id).unwrap(),
@@ -326,7 +346,7 @@ mod tests {
assert!(store.start(interrupted).is_err());
let failed = request(now());
let attempt = begin(&store, failed.clone());
- attempt.fail("example prepare failure").unwrap();
+ smol::block_on(attempt.fail("example prepare failure")).unwrap();
drop(attempt);
assert_eq!(
store.status(&failed.request_id).unwrap(),
@@ -371,6 +391,25 @@ mod tests {
assert!(store.start(old).is_err());
}
+ #[test]
+ fn a_server_clock_behind_the_client_still_accepts_requests() {
+ let dir = tempfile::tempdir().unwrap();
+ let store = Store {
+ path: dir.path().join("receipts.json"),
+ };
+ let ahead = request(now() + 24 * 60 * 60);
+ assert_eq!(
+ store.status(&ahead.request_id).unwrap(),
+ ImportSessionStatus::NotFound
+ );
+ let attempt = begin(&store, ahead.clone());
+ assert_eq!(
+ store.status(&ahead.request_id).unwrap(),
+ ImportSessionStatus::Running
+ );
+ drop(attempt);
+ }
+
#[test]
fn full_or_unreadable_receipts_refuse_new_imports() {
let dir = tempfile::tempdir().unwrap();
diff --git a/wezterm-mux-server-impl/src/sessionhandler.rs b/wezterm-mux-server-impl/src/sessionhandler.rs
index af94d74f..3c8697ea 100644
--- a/wezterm-mux-server-impl/src/sessionhandler.rs
+++ b/wezterm-mux-server-impl/src/sessionhandler.rs
@@ -2231,7 +2231,7 @@ impl SessionHandler {
}
#[cfg(unix)]
spawn_into_main_thread(async move {
- send_response(crate::session_import::status(&request.request_id).map(|status| {
+ send_response(crate::session_import::status(request.request_id).await.map(|status| {
Pdu::GetImportSessionStatusResponse(codec::GetImportSessionStatusResponse { status })
}));
}).detach();