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.
Rust agentagent-orchestrationaiai-agentsclaude-codecodexcoding-agentlinuxmacosmultiplayermultiplexerrustterminalterminal-emulatorterminal-multiplexertmuxtuiweztermwindows
mobile: the nine high findings of the review
RoversXd507ce21b12e
diff --git a/android/app/src/main/AndroidManifest.xml b/android/app/src/main/AndroidManifest.xmlindex b13706a3..bdb1cfa0 100644--- a/android/app/src/main/AndroidManifest.xml+++ b/android/app/src/main/AndroidManifest.xml@@ -2,11 +2,16 @@<manifest xmlns:android="http://schemas.android.com/apk/res/android"><uses-permission android:name="android.permission.INTERNET" /><uses-permission android:name="android.permission.VIBRATE" />+ <!-- Nothing here is backed up or moved to another device: the+ private keys and passwords are bound to this device's keystore,+ and a copy of their file elsewhere would be unreadable at best. --><applicationandroid:label="ThinkTerm"android:icon="@mipmap/ic_launcher"android:theme="@style/Theme.ThinkTerm"- android:supportsRtl="true">+ android:supportsRtl="true"+ android:allowBackup="false"+ android:dataExtractionRules="@xml/data_extraction_rules"><activityandroid:name=".MainActivity"android:exported="true"diff --git a/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt b/android/app/src/main/java/com/roversx/thinkterm/HostStore.ktindex b7d1e1c3..375d9818 100644--- a/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/HostStore.kt@@ -187,20 +187,81 @@ class HostStore(context: Context) {private companion object {const val KEY = "hosts.v1"- /// Keystore-backed preferences. If the device refuses (a broken- /// keystore on an emulator), plain preferences keep the app usable.- fun openSecrets(app: Context): SharedPreferences = try {+ const val SECRETS = "thinkterm-secrets"++ /// Keystore-backed preferences. A file whose keyset the keystore+ /// can no longer open (a restore onto another device) is thrown+ /// away and made afresh: its secrets were lost with the key. If+ /// the keystore refuses altogether, the secrets live in memory+ /// for this run -- never in a file in the clear.+ fun openSecrets(app: Context): SharedPreferences {+ try {+ return openEncrypted(app)+ } catch (e: Throwable) {+ Log.w("thinkterm", "encrypted preferences unreadable, starting them over: $e")+ }+ try {+ app.deleteSharedPreferences(SECRETS)+ return openEncrypted(app)+ } catch (e: Throwable) {+ Log.w("thinkterm", "encrypted preferences unavailable: $e")+ }+ return MemoryPreferences()+ }++ private fun openEncrypted(app: Context): SharedPreferences {val key = MasterKey.Builder(app).setKeyScheme(MasterKey.KeyScheme.AES256_GCM).build()- EncryptedSharedPreferences.create(+ return EncryptedSharedPreferences.create(app,- "thinkterm-secrets",+ SECRETS,key,EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM,)- } catch (e: Throwable) {- Log.w("thinkterm", "encrypted preferences unavailable: $e")- app.getSharedPreferences("thinkterm-secrets-plain", Context.MODE_PRIVATE)+ }+ }+}++/// Preferences that last for the run only: the stand-in for the+/// encrypted store when the keystore is out of order.+private class MemoryPreferences : SharedPreferences {+ private val values = HashMap<String, Any?>()+ private val listeners = HashSet<SharedPreferences.OnSharedPreferenceChangeListener>()++ override fun getAll(): MutableMap<String, *> = HashMap(values)+ override fun getString(key: String?, defValue: String?): String? = values[key] as? String ?: defValue+ @Suppress("UNCHECKED_CAST")+ override fun getStringSet(key: String?, defValues: MutableSet<String>?): MutableSet<String>? =+ (values[key] as? Set<String>)?.toMutableSet() ?: defValues+ override fun getInt(key: String?, defValue: Int): Int = values[key] as? Int ?: defValue+ override fun getLong(key: String?, defValue: Long): Long = values[key] as? Long ?: defValue+ override fun getFloat(key: String?, defValue: Float): Float = values[key] as? Float ?: defValue+ override fun getBoolean(key: String?, defValue: Boolean): Boolean = values[key] as? Boolean ?: defValue+ override fun contains(key: String?): Boolean = values.containsKey(key)+ override fun edit(): SharedPreferences.Editor = Editor()+ override fun registerOnSharedPreferenceChangeListener(l: SharedPreferences.OnSharedPreferenceChangeListener) { listeners.add(l) }+ override fun unregisterOnSharedPreferenceChangeListener(l: SharedPreferences.OnSharedPreferenceChangeListener) { listeners.remove(l) }++ private inner class Editor : SharedPreferences.Editor {+ private val puts = HashMap<String, Any?>()+ private val removes = HashSet<String>()+ private var clear = false++ override fun putString(key: String?, value: String?) = also { if (key != null) puts[key] = value }+ override fun putStringSet(key: String?, values: MutableSet<String>?) = also { if (key != null) puts[key] = values?.toSet() }+ override fun putInt(key: String?, value: Int) = also { if (key != null) puts[key] = value }+ override fun putLong(key: String?, value: Long) = also { if (key != null) puts[key] = value }+ override fun putFloat(key: String?, value: Float) = also { if (key != null) puts[key] = value }+ override fun putBoolean(key: String?, value: Boolean) = also { if (key != null) puts[key] = value }+ override fun remove(key: String?) = also { if (key != null) removes.add(key) }+ override fun clear() = also { clear = true }+ override fun commit(): Boolean { apply(); return true }+ override fun apply() {+ if (clear) values.clear()+ for (k in removes) values.remove(k)+ for ((k, v) in puts) if (v == null) values.remove(k) else values[k] = v+ val changed = removes + puts.keys+ for (l in listeners.toList()) for (k in changed) l.onSharedPreferenceChanged(this@MemoryPreferences, k)}}}diff --git a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.ktindex 7a06972c..af0816de 100644--- a/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt+++ b/android/app/src/main/java/com/roversx/thinkterm/TerminalModel.kt@@ -251,7 +251,11 @@ class TerminalModel(// MARK: inputfun key(name: String, ctrl: Boolean = false, alt: Boolean = false, shift: Boolean = false) {- core.key(name, ctrl || takeCtrl(), alt || takeAlt(), shift)+ // A sticky modifier is spent by the next key whether or not that+ // key brought the modifier itself, so it never lingers past it.+ val stickyCtrl = takeCtrl()+ val stickyAlt = takeAlt()+ core.key(name, ctrl || stickyCtrl, alt || stickyAlt, shift)}/// Text from the keyboard. A sticky Ctrl or Alt turns a single@@ -535,10 +539,24 @@ object Assets {fun install(context: Context) {for (name in faces) {val out = java.io.File(context.filesDir, name)- if (out.exists() && out.length() > 0) continue+ // The APK's copy is the truth: a file of another size is a+ // copy that was cut short (or a font that changed) and is+ // made again. An unknown size settles for a file that exists.+ val wanted = try {+ context.assets.openFd(name).use { it.length }+ } catch (e: Throwable) {+ -1L+ }+ if (out.exists() && out.length() > 0 && (wanted < 0 || out.length() == wanted)) continue+ // Written beside its name and renamed into place, so a copy+ // interrupted half-way never passes for a font.+ val part = java.io.File(context.filesDir, "$name.part")try {- context.assets.open(name).use { input -> out.outputStream().use { input.copyTo(it) } }+ context.assets.open(name).use { input -> part.outputStream().use { input.copyTo(it) } }+ if (wanted >= 0 && part.length() != wanted) throw java.io.IOException("short copy")+ if (!part.renameTo(out)) throw java.io.IOException("rename failed")} catch (e: Throwable) {+ part.delete()Log.w("thinkterm", "font $name not installed: $e")}}diff --git a/android/app/src/main/res/xml/data_extraction_rules.xml b/android/app/src/main/res/xml/data_extraction_rules.xmlnew file mode 100644index 00000000..2d950ddb--- /dev/null+++ b/android/app/src/main/res/xml/data_extraction_rules.xml@@ -0,0 +1,19 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- The keystore-bound secrets never leave the device; with them out,+ the host list alone would only mislead, so nothing goes. -->+<data-extraction-rules>+ <cloud-backup disableIfNoEncryptionCapabilities="true">+ <exclude domain="root" />+ <exclude domain="file" />+ <exclude domain="database" />+ <exclude domain="sharedpref" />+ <exclude domain="external" />+ </cloud-backup>+ <device-transfer>+ <exclude domain="root" />+ <exclude domain="file" />+ <exclude domain="database" />+ <exclude domain="sharedpref" />+ <exclude domain="external" />+ </device-transfer>+</data-extraction-rules>diff --git a/ios/Sources/TerminalInputView.swift b/ios/Sources/TerminalInputView.swiftindex 57ea1653..756455b0 100644--- a/ios/Sources/TerminalInputView.swift+++ b/ios/Sources/TerminalInputView.swift@@ -297,24 +297,34 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDelreturn row * (s.cols + 1) + col}- /// The cell under a point in the view, clamped into the pane.+ /// The cell under a point UIKit hands the text input, clamped into+ /// the pane. Those points are in the scroll view's coordinates, which+ /// start at the content offset, half-way down the runway.private func cell(under point: CGPoint) -> (row: Int, col: Int)? {guard let s = currentScreen(), s.cell[0] > 0, s.cell[1] > 0 else { return nil }- let col = Int(((point.x - s.origin[0]) / s.cell[0]).rounded(.down))- let row = Int(((point.y - s.origin[1]) / s.cell[1]).rounded(.down))+ let x = point.x - contentOffset.x+ let y = point.y - contentOffset.y+ let col = Int(((x - s.origin[0]) / s.cell[0]).rounded(.down))+ let row = Int(((y - s.origin[1]) / s.cell[1]).rounded(.down))return (min(max(row, 0), s.rows - 1), min(max(col, 0), s.cols - 1))}+ /// A cell's rect for UIKit, in the scroll view's coordinates.private func rect(row: Int, col: Int, cols: Int = 1) -> CGRect {guard let s = currentScreen() else { return .zero }return CGRect(- x: s.origin[0] + Double(col) * s.cell[0],- y: s.origin[1] + Double(row) * s.cell[1],+ x: contentOffset.x + s.origin[0] + Double(col) * s.cell[0],+ y: contentOffset.y + s.origin[1] + Double(row) * s.cell[1],width: Double(cols) * s.cell[0],height: s.cell[1])}+ /// The App's cursor rect, in the scroll view's coordinates.+ private var cursorRectForText: CGRect {+ (model?.cursorRect ?? .zero).offsetBy(dx: contentOffset.x, dy: contentOffset.y)+ }+// MARK: UITextInput -- marked text (after the rows)var markedTextRange: UITextRange? {@@ -491,7 +501,7 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel// MARK: UITextInput -- geometryfunc firstRect(for range: UITextRange) -> CGRect {- guard let r = range as? Range, let a = cell(at: r.a) else { return model?.cursorRect ?? .zero }+ guard let r = range as? Range, let a = cell(at: r.a) else { return cursorRectForText }let last = cell(at: max(r.b - 1, r.a)) ?? alet cols = last.row == a.row ? last.col - a.col + 1 : (currentScreen()?.cols ?? 1) - a.colreturn rect(row: a.row, col: a.col, cols: max(cols, 1))@@ -502,7 +512,7 @@ final class TerminalInputView: UIScrollView, UITextInput, UIGestureRecognizerDel/// tapped cell would only mislead.func caretRect(for position: UITextPosition) -> CGRect {guard let p = position as? Pos, let c = cell(at: p.i) else {- var r = model?.cursorRect ?? .zero+ var r = cursorRectForTextr.size.width = 0return r}diff --git a/ios/Sources/TerminalModel.swift b/ios/Sources/TerminalModel.swiftindex 4c7a3e4a..d05c510d 100644--- a/ios/Sources/TerminalModel.swift+++ b/ios/Sources/TerminalModel.swift@@ -214,7 +214,11 @@ final class TerminalModel: ObservableObject, @unchecked Sendable {// MARK: inputfunc key(_ name: String, ctrl: Bool = false, alt: Bool = false, shift: Bool = false) {- core.key(name: name, ctrl: ctrl || takeSticky(\.ctrlSticky), alt: alt || takeSticky(\.altSticky), shift: shift)+ // A sticky modifier is spent by the next key whether or not that+ // key brought the modifier itself, so it never lingers past it.+ let stickyCtrl = takeSticky(\.ctrlSticky)+ let stickyAlt = takeSticky(\.altSticky)+ core.key(name: name, ctrl: ctrl || stickyCtrl, alt: alt || stickyAlt, shift: shift)}/// Text from the keyboard. A sticky Ctrl or Alt turns a singlediff --git a/thinkterm-mobile/src/core.rs b/thinkterm-mobile/src/core.rsindex 3bf3763b..567a2c22 100644--- a/thinkterm-mobile/src/core.rs+++ b/thinkterm-mobile/src/core.rs@@ -71,8 +71,9 @@ pub enum Cmd {painter: Box<dyn GlyphPainter>,},Disconnect,- /// From the network thread.- Net(Net),+ /// From the network thread; `serial` names the link it belongs to,+ /// so a retiring thread's last words never reach its successor.+ Net { serial: u64, net: Net },/// The first dial finished.Dialed(Result<(), String>),/// The attach handshake finished.@@ -157,6 +158,9 @@ pub enum Cmd {/// The surface currently lent, if any.struct Target {generation: u64,+ /// The shell's native layer or window, kept so the GPU state can be+ /// remade on it without a fresh attach.+ layer: usize,width: u32,height: u32,scale: f64,@@ -199,6 +203,8 @@ struct State {app: Option<Rc<MobileApp>>,target: Option<Target>,next_generation: u64,+ /// One per link made; a network event from an older one is dropped.+ link_serial: u64,animating: bool,stats: Stats,notify: Arc<dyn Notify>,@@ -237,6 +243,7 @@ pub fn run(cmd_tx: Sender<Cmd>, rx: Receiver<Cmd>, notify: Box<dyn Notify>) {app: None,target: None,next_generation: 1,+ link_serial: 0,animating: false,stats: Stats::default(),notify,@@ -334,7 +341,7 @@ impl State {self.disconnect();self.set_status("disconnected");}- Cmd::Net(net) => self.on_net(net),+ Cmd::Net { serial, net } => self.on_net(serial, net),Cmd::Dialed(outcome) => self.on_dialed(outcome),Cmd::Attached(outcome) => self.on_attached(outcome),Cmd::Key {@@ -627,10 +634,12 @@ impl State {self.glyph_platform = Some(Rc::new(GlyphSeams::new(painter)));let tx = self.cmd_tx.clone();+ self.link_serial += 1;+ let serial = self.link_serial;let deliver: Box<dyn Fn() -> Box<dyn Fn(Net) + Send>> = Box::new(move || {let tx = tx.clone();Box::new(move |net| {- let _ = tx.send(Cmd::Net(net));+ let _ = tx.send(Cmd::Net { serial, net });})});let link = SshLink::new(params.ssh.clone(), deliver);@@ -661,25 +670,60 @@ impl State {link.shutdown();}if let Some(app) = self.app.take() {+ // Cut the link's hold on the App, then let every task on the+ // wire see the link gone and finish, so nothing but this+ // handle is left holding it.+ app.retire();+ self.pool.run_until_stalled();// The device, the pipeline and the surface come back to the// core for the next connection (or the demo).match App::into_gpu(app) {Ok(gpu) => self.gpu = Some(gpu),Err(app) => {- // A task still holds the App: let it go with its GPU- // state; the shell's next attach makes a fresh one.+ // Something still holds the App. It must never draw+ // again on a window the shell may release: take the+ // surface from it and unhook its frame handler, then+ // remake the GPU state on the target still attached.+ app.with_gpu(|gpu| gpu.detach_surface());+ self.platform.set_frame_handler(Box::new(|| {}));drop(app);self.gpu = None;- self.target = None;- self.notify.on_log(- "the App was still in use; its GPU state went with it -- attach the surface again".into(),- );+ self.notify+ .on_log("the App was still in use; remaking the GPU state".into());+ self.remake_gpu();}}+ // Every timer and interval belonged to that App.+ self.platform.clear_timers();}self.conn = Conn::Idle;}+ /// A fresh device and swapchain on the surface the shell still lends,+ /// for when the old ones went away with a retired App.+ fn remake_gpu(&mut self) {+ let Some(target) = self.target.as_ref() else {+ return;+ };+ let (layer, width, height) = (target.layer, target.width, target.height);+ let made = self.surface_from_layer(layer).and_then(|surface| {+ futures::executor::block_on(Gpu::from_surface(&self.instance, surface, width, height))+ });+ match made {+ Ok(gpu) => {+ let info = gpu.adapter_info.name.clone();+ self.gpu = Some(gpu);+ self.notify.on_log(format!("gpu ready again: {info}"));+ }+ Err(err) => {+ self.target = None;+ self.notify.on_log(format!(+ "remaking the GPU state failed: {err:#} -- attach the surface again"+ ));+ }+ }+ }+fn on_dialed(&mut self, outcome: Result<(), String>) {match outcome {Ok(()) => {@@ -696,7 +740,17 @@ impl State {}}- fn on_net(&mut self, net: Net) {+ fn on_net(&mut self, serial: u64, net: Net) {+ if serial != self.link_serial {+ // A thread of an earlier link, saying its goodbyes: the link+ // it speaks for is gone, and the current one must not hear+ // them as its own.+ if let Net::Closed(reason) = net {+ self.notify+ .on_log(format!("an earlier connection ended: {reason}"));+ }+ return;+ }let Some(link) = self.link.clone() else {return;};@@ -960,6 +1014,7 @@ impl State {self.next_generation += 1;self.target = Some(Target {generation,+ layer,width,height,scale,diff --git a/thinkterm-mobile/src/platform.rs b/thinkterm-mobile/src/platform.rsindex e16acaf4..54dd5185 100644--- a/thinkterm-mobile/src/platform.rs+++ b/thinkterm-mobile/src/platform.rs@@ -127,6 +127,12 @@ impl MobilePlatform {pub fn frame_pending(&self) -> bool {self.frame_requested.get()}++ /// Drop every timer and interval: they were an App's, and it is gone.+ pub fn clear_timers(&self) {+ self.timers.borrow_mut().clear();+ self.intervals.borrow_mut().clear();+ }}impl Platform for MobilePlatform {diff --git a/thinkterm-mobile/src/ssh.rs b/thinkterm-mobile/src/ssh.rsindex fc287930..9c0e0937 100644--- a/thinkterm-mobile/src/ssh.rs+++ b/thinkterm-mobile/src/ssh.rs@@ -141,10 +141,12 @@ async fn run().await.context("connecting timed out")?;+ let mut session = dial.context("ssh transport")?;+ // Only a key the check let through is worth remembering: the shells+ // pin whatever arrives here, and a mismatch must not replace the pin.if let Some(fingerprint) = seen.lock().unwrap().clone() {deliver(Net::HostKey(fingerprint));}- let mut session = dial.context("ssh transport")?;let auth = match ¶ms.auth {Auth::KeyPath(path) => {@@ -190,29 +192,48 @@ async fn run(channel.exec(true, command).await.context("exec")?;deliver(Net::Connected);+ // A write waits for the remote's window, and the window only grows+ // through messages the reader takes in; russh parks its session loop+ // on a full inbound queue. So the writer runs apart from the reader,+ // and a stalled write never stops the reading.+ let (mut reader, writer) = channel.split();+ let mut sender = tokio::spawn(async move {+ while let Some(out) = out_rx.recv().await {+ match out {+ Out::Bytes(bytes) => writer+ .data(&bytes[..])+ .await+ .context("writing to the channel")?,+ Out::Close => break,+ }+ }+ let _ = writer.eof().await;+ let _ = writer.close().await;+ Ok::<(), anyhow::Error>(())+ });loop {tokio::select! {- out = out_rx.recv() => match out {- Some(Out::Bytes(bytes)) => {- channel.data(&bytes[..]).await.context("writing to the channel")?;- }- Some(Out::Close) | None => {- let _ = channel.eof().await;- let _ = channel.close().await;- let _ = session- .disconnect(russh::Disconnect::ByApplication, "closed", "")- .await;- return Ok("closed by the client".into());- }- },- msg = channel.wait() => match msg {+ sent = &mut sender => {+ let _ = session+ .disconnect(russh::Disconnect::ByApplication, "closed", "")+ .await;+ return match sent {+ Ok(Ok(())) => Ok("closed by the client".into()),+ Ok(Err(err)) => Err(err),+ Err(err) => Err(anyhow!("the writer ended: {err}")),+ };+ }+ msg = reader.wait() => match msg {Some(ChannelMsg::Data { data }) => deliver(Net::Data(data.to_vec())),Some(ChannelMsg::ExtendedData { data, .. }) => {deliver(Net::Stderr(String::from_utf8_lossy(&data).to_string()))}Some(ChannelMsg::ExitStatus { exit_status }) => deliver(Net::Exit(exit_status)),Some(ChannelMsg::Eof) => {}- Some(ChannelMsg::Close) | None => return Ok("the remote command ended".into()),+ Some(ChannelMsg::Close) | None => {+ sender.abort();+ return Ok("the remote command ended".into());+ }Some(_) => {}},}diff --git a/thinkterm-web/src/app.rs b/thinkterm-web/src/app.rsindex 68a3fec0..dca28151 100644--- a/thinkterm-web/src/app.rs+++ b/thinkterm-web/src/app.rs@@ -444,6 +444,9 @@ pub struct App<P: Platform, L: Link> {retry_pending: Cell<bool>,/// When the pending timer is due, so a nearer one can replace it.retry_due: Cell<f64>,+ /// Set once the App is let go: a tick that still finds it (an+ /// interval cannot be cancelled) does nothing more.+ retired: Cell<bool>,}/// How large the glyph atlas is allowed to get.@@ -631,6 +634,7 @@ impl<P: Platform, L: Link> App<P, L> {frame_requested: Cell::new(false),retry_pending: Cell::new(false),retry_due: Cell::new(0.0),+ retired: Cell::new(false),});let weak = Rc::downgrade(&app);app.platform.set_frame_handler(Box::new(move || {@@ -1289,10 +1293,11 @@ impl<P: Platform, L: Link> App<P, L> {}inner.reconnect_pending = true;}- let app = Rc::clone(self);+ let weak = Rc::downgrade(self);self.platform.set_timeout(delay_ms.max(0.0),Box::new(move || {+ let Some(app) = weak.upgrade() else { return };app.inner.borrow_mut().reconnect_pending = false;let task = Rc::clone(&app).try_reconnect();app.spawn(task);@@ -2724,10 +2729,11 @@ impl<P: Platform, L: Link> App<P, L> {}inner.session_refresh_pending = true;}- let app = Rc::clone(self);+ let weak = Rc::downgrade(self);self.platform.set_timeout(150.0,Box::new(move || {+ let Some(app) = weak.upgrade() else { return };app.inner.borrow_mut().session_refresh_pending = false;let task = {let app = Rc::clone(&app);@@ -3453,9 +3459,15 @@ impl<P: Platform, L: Link> App<P, L> {/// `refresh_layout`, a moment from now, so a burst of pushes is one/// listing.fn refresh_layout_soon(self: &Rc<Self>) {- let app = Rc::clone(self);- self.platform- .set_timeout(150.0, Box::new(move || app.refresh_layout()));+ let weak = Rc::downgrade(self);+ self.platform.set_timeout(+ 150.0,+ Box::new(move || {+ if let Some(app) = weak.upgrade() {+ app.refresh_layout();+ }+ }),+ );}/// Ask the server again every so often, whatever the pushes said:@@ -3466,7 +3478,9 @@ impl<P: Platform, L: Link> App<P, L> {every_ms as f64,Box::new(move || {if let Some(app) = weak.upgrade() {- app.refresh_layout();+ if !app.retired.get() {+ app.refresh_layout();+ }}}),);@@ -3560,12 +3574,14 @@ impl<P: Platform, L: Link> App<P, L> {self.close_pane();} else {// Back to a plain × when the moment passes.- let app = Rc::clone(self);+ let weak = Rc::downgrade(self);self.platform.set_timeout(CLOSE_CONFIRM_MS + 50.0,Box::new(move || {- let inner = app.inner.borrow();- Self::render_strip(&inner);+ if let Some(app) = weak.upgrade() {+ let inner = app.inner.borrow();+ Self::render_strip(&inner);+ }}),);}@@ -3933,16 +3949,22 @@ impl<P: Platform, L: Link> App<P, L> {/// Blink the cursor: a half-second tick that hides it every other/// beat. Intervals cannot be cancelled, so the tick starts once and- /// idles while blinking is off.+ /// idles while blinking is off. It holds the App weakly: a strong+ /// reference here would keep a retired App (and its GPU state)+ /// alive for the life of the platform.fn set_blinking(self: &Rc<Self>, on: bool) {let mut inner = self.inner.borrow_mut();inner.blink_shown = true;if on && !inner.blink_ticking {inner.blink_ticking = true;- let app = Rc::clone(self);+ let weak = Rc::downgrade(self);inner.platform.set_interval(530.0,Box::new(move || {+ let Some(app) = weak.upgrade() else { return };+ if app.retired.get() {+ return;+ }let mut inner = app.inner.borrow_mut();if !inner.settings.cursor_blink || inner.panes.is_empty() {return;@@ -4445,17 +4467,25 @@ impl<P: Platform, L: Link> App<P, L> {f(&mut self.inner.borrow_mut().gpu)}- /// Let the link go and take the GPU state back, for a platform that- /// keeps its device across connections. Fails (handing the App back)- /// while something else still holds it -- a task on the wire, say.+ /// Let the link go, ahead of `into_gpu`. The link's handlers hold the+ /// App and the App holds the link; cutting that, and telling the+ /// link's pending requests they will not be answered, lets every task+ /// on the wire finish once the executor runs again. Ticks that still+ /// reach the App afterwards do nothing.+ pub fn retire(&self) {+ self.retired.set(true);+ let inner = self.inner.borrow();+ inner.link.set_push_handler(Box::new(|_| {}));+ inner.link.set_close_handler(Box::new(|_| {}));+ inner.link.shutdown();+ }++ /// Take the GPU state back, for a platform that keeps its device+ /// across connections. Fails (handing the App back) while something+ /// else still holds it -- a task on the wire, say; `retire` first and+ /// run the executor to give those a chance to finish.pub fn into_gpu(app: Rc<Self>) -> std::result::Result<Gpu, Rc<Self>> {- {- // The link's handlers hold the App; the App holds the link.- let inner = app.inner.borrow();- inner.link.set_push_handler(Box::new(|_| {}));- inner.link.set_close_handler(Box::new(|_| {}));- inner.link.shutdown();- }+ app.retire();Rc::try_unwrap(app).map(|app| app.inner.into_inner().gpu)}