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
feat(snippets): show the plugin server's snippets in the desktop panel
RoversXe4fb07559baf
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex b4f4f4d1..452e8acf 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -405,6 +405,7 @@ right-new-snippet = Neues Snippetright-search = Suchenright-no-snippets = Keine Snippetsright-no-matching-snippets = Keine passenden Snippets+right-snippets-unavailable = Snippets sind gerade nicht verfügbarright-edit-snippet = Snippet bearbeitenright-snippet = Snippetright-personal-vault = Persönlicher Vault@@ -837,6 +838,7 @@ web-tip-archive = Dieses Projekt archivieren (beendet seine Programme)web-tip-pin = Anheftenweb-tip-unpin = Lösenweb-tip-delete-thread = Diesen Thread löschen und seine Programme beenden.+web-tip-delete-snippet = Snippet löschenweb-confirm-delete = löschen?web-confirm-close = schließen?web-tip-close-pane = Dieses Pane schließen und sein Programm beenden.diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex 7514eded..f9bda4e7 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -405,6 +405,7 @@ right-new-snippet = New Snippetright-search = Searchright-no-snippets = No snippetsright-no-matching-snippets = No matching snippets+right-snippets-unavailable = Snippets are unavailable right nowright-edit-snippet = Edit Snippetright-snippet = Snippetright-personal-vault = Personal vault@@ -829,6 +830,7 @@ web-tip-archive = Archive this project (ends its programs)web-tip-pin = Pinweb-tip-unpin = Unpinweb-tip-delete-thread = Delete this thread and end its programs.+web-tip-delete-snippet = Delete snippetweb-confirm-delete = delete?web-confirm-close = close?web-tip-close-pane = Close this pane and end its program.diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex 59807ef5..8bd47d9c 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -405,6 +405,7 @@ right-new-snippet = Nouvel extraitright-search = Rechercherright-no-snippets = Aucun extraitright-no-matching-snippets = Aucun extrait correspondant+right-snippets-unavailable = Les extraits sont indisponibles pour le momentright-edit-snippet = Modifier l’extraitright-snippet = Extraitright-personal-vault = Coffre personnel@@ -834,6 +835,7 @@ web-tip-archive = Archiver ce projet (met fin à ses programmes)web-tip-pin = Épinglerweb-tip-unpin = Désépinglerweb-tip-delete-thread = Supprimer cette session et mettre fin à ses programmes.+web-tip-delete-snippet = Supprimer l’extraitweb-confirm-delete = supprimer ?web-confirm-close = fermer ?web-tip-close-pane = Fermer ce volet et mettre fin à son programme.diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex d2088f42..68cc1040 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -396,6 +396,7 @@ right-new-snippet = 新しいスニペットright-search = 検索right-no-snippets = スニペットはありませんright-no-matching-snippets = 一致するスニペットはありません+right-snippets-unavailable = スニペットは現在利用できませんright-edit-snippet = スニペットを編集right-snippet = スニペットright-personal-vault = 個人用保管庫@@ -815,6 +816,7 @@ web-tip-archive = このプロジェクトをアーカイブ(プログラムをweb-tip-pin = ピン留めweb-tip-unpin = ピン留めを解除web-tip-delete-thread = このセッションを削除してプログラムを終了します。+web-tip-delete-snippet = スニペットを削除web-confirm-delete = 削除?web-confirm-close = 閉じる?web-tip-close-pane = このペインを閉じてプログラムを終了します。diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex afd732c5..c0041110 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -396,6 +396,7 @@ right-new-snippet = 新建片段right-search = 搜索right-no-snippets = 没有片段right-no-matching-snippets = 没有匹配的片段+right-snippets-unavailable = 片段暂时不可用right-edit-snippet = 编辑片段right-snippet = 片段right-personal-vault = 个人库@@ -815,6 +816,7 @@ web-tip-archive = 归档这个项目(会结束其中的程序)web-tip-pin = 置顶web-tip-unpin = 取消置顶web-tip-delete-thread = 删除这个会话并结束其中的程序。+web-tip-delete-snippet = 删除片段web-confirm-delete = 删除?web-confirm-close = 关闭?web-tip-close-pane = 关闭这个窗格并结束其中的程序。diff --git a/wezterm-gui/src/snippets.rs b/wezterm-gui/src/snippets.rsindex babf5ece..e780148d 100644--- a/wezterm-gui/src/snippets.rs+++ b/wezterm-gui/src/snippets.rs@@ -1,31 +1,67 @@-//! ThinkTerm command snippets shown in the right sidebar: this desktop's copy-//! of the `thinkterm-snippets` store, kept in the GUI's data directory.+//! ThinkTerm command snippets shown in the right sidebar.+//!+//! The snippets live in the plugin host, the thinkterm-plugin-server process,+//! which keeps them and does everything with them: searching, saving,+//! deleting, making the text a pane is sent (see thinkterm-snippets+//! `wire`). A window's panel is only a view of it: each window keeps its+//! own search and the rows sent for it (thinkterm-snippets `view`), and+//! forwards what the user does. This holds what the windows share: the one+//! session with the host, and the windows to tell when the snippets change.+//! A browser's panel is another view of the same.+//!+//! The session is let go once no window has painted the panel for a while,+//! and the windows' rows with it; the next paint asks again.+use crate::termwindow::{TermWindow, TermWindowNotif};use anyhow::Result;-use parking_lot::Mutex;+use parking_lot::{Mutex, MutexGuard};+use serde::de::DeserializeOwned;use std::path::{Path, PathBuf};-use std::time::{SystemTime, UNIX_EPOCH};-use thinkterm_snippets::SnippetStore;+use std::time::{Duration, Instant};+use thinkterm_plugin_channel::client::{Host, Notice, Session};+use thinkterm_snippets::wire::{Event, Request, PLUGIN};+use window::{Window, WindowOps};-pub use thinkterm_snippets::SnippetRecord;+pub use thinkterm_snippets::wire::{Row, Saved, Snippet};-lazy_static::lazy_static! {- static ref SNIPPET_STORE: Mutex<SnippetStore> =- Mutex::new(thinkterm_snippets::file::load(&snippets_store_path()).unwrap_or_else(|err| {- log::warn!("failed to load ThinkTerm snippets store: {err:#}");- SnippetStore::default()- }));+/// How long the panel may go unpainted before the session is let go.+const RELEASE_AFTER: Duration = Duration::from_secs(120);+/// How often that is looked at.+const RELEASE_CHECK: Duration = Duration::from_secs(15);++struct Shared {+ session: Option<Session>,+ /// Counts sessions, so a release check stops with the one it watched.+ generation: u64,+ /// The windows that have painted the panel since the session started:+ /// the ones told when the snippets change, or the rows are let go. A+ /// handful at most; one that has closed ignores what it is told.+ windows: Vec<Window>,+ /// Why the host cannot be reached, while it cannot.+ trouble: Option<String>,+ last_used: Option<Instant>,}-pub fn snippets_store_path() -> PathBuf {- crate::native_paths::data_file("snippets.json")+static SHARED: Mutex<Shared> = parking_lot::const_mutex(Shared {+ session: None,+ generation: 0,+ windows: Vec::new(),+ trouble: None,+ last_used: None,+});++/// What a window's panel has to show.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum Availability {+ Ready,+ /// The host has not answered yet.+ Loading,+ /// The host cannot be reached; why.+ Unavailable(String),}-fn now_ms() -> u64 {- SystemTime::now()- .duration_since(UNIX_EPOCH)- .map(|duration| duration.as_millis().min(u128::from(u64::MAX)) as u64)- .unwrap_or(0)+pub fn snippets_store_path() -> PathBuf {+ crate::native_paths::data_file("snippets.json")}/// Whether `path` reads as a snippet store, as an imported backup must.@@ -33,45 +69,224 @@ pub(crate) fn check_snippet_store(path: &Path) -> Result<()> {thinkterm_snippets::file::load(path).map(drop)}-fn save(store: &SnippetStore) -> Result<()> {- thinkterm_snippets::file::save(&snippets_store_path(), store)+/// The shared state, marked as in use, with a session to the host. On the+/// GUI thread: it may start the release check.+fn shared_in_use() -> MutexGuard<'static, Shared> {+ let mut shared = SHARED.lock();+ shared.last_used = Some(Instant::now());+ if shared.session.is_none() {+ let started = Host::for_this_build().and_then(|host| Session::start(host, on_notice));+ match started {+ Ok(session) => {+ shared.session = Some(session);+ shared.generation += 1;+ release_when_idle(shared.generation);+ }+ Err(err) => shared.trouble = Some(format!("{err:#}")),+ }+ }+ shared}-/// The snippets the panel shows for `query`; see `SnippetStore::matching`.-pub fn matching_snippets(query: &str) -> Vec<SnippetRecord> {- SNIPPET_STORE.lock().matching(query).cloned().collect()+/// `window` paints the panel: it is told when the snippets change, and the+/// session is kept.+pub fn in_use(window: &Window) {+ let mut shared = shared_in_use();+ if !shared.windows.contains(window) {+ shared.windows.push(window.clone());+ }+}++/// Why the host cannot be reached, while it cannot.+pub fn trouble() -> Option<String> {+ SHARED.lock().trouble.clone()+}++/// Has every window that shows the panel apply `change` to itself.+fn tell_windows(change: fn(&mut TermWindow)) {+ let windows: Vec<Window> = SHARED.lock().windows.iter().cloned().collect();+ promise::spawn::spawn_into_main_thread(async move {+ for window in windows {+ let repaint = window.clone();+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ change(term_window);+ repaint.invalidate();+ })));+ }+ })+ .detach();+}++fn on_notice(notice: Notice) {+ match notice {+ // Whatever the host said before, it is asked again.+ Notice::Connected => {+ SHARED.lock().trouble = None;+ tell_windows(TermWindow::snippets_changed);+ }+ Notice::Event { plugin, body } if plugin == PLUGIN => {+ if let Ok(Event::Changed) = serde_json::from_value(body) {+ tell_windows(TermWindow::snippets_changed);+ }+ }+ Notice::Event { .. } => {}+ Notice::Trouble(why) => {+ SHARED.lock().trouble = Some(why);+ // Rows already on show stay; an empty panel says why.+ tell_windows(|_| {});+ }+ }}-pub fn matching_snippet_count(query: &str) -> usize {- SNIPPET_STORE.lock().matching(query).count()+/// Lets the session go once no window has painted the panel for a while,+/// and the windows' rows with it -- without asking them to paint, which+/// would only ask for them again.+fn release_when_idle(generation: u64) {+ promise::spawn::spawn(async move {+ loop {+ smol::Timer::after(RELEASE_CHECK).await;+ let mut shared = SHARED.lock();+ if shared.generation != generation || shared.session.is_none() {+ return;+ }+ let idle = shared+ .last_used+ .map_or(true, |used| used.elapsed() >= RELEASE_AFTER);+ if !idle {+ continue;+ }+ shared.session = None;+ shared.trouble = None;+ for window in shared.windows.drain(..) {+ window.notify(TermWindowNotif::Apply(Box::new(|term_window| {+ term_window.snippets_released();+ })));+ }+ return;+ }+ })+ .detach();}-pub fn get_snippet(id: &str) -> Option<SnippetRecord> {- SNIPPET_STORE.lock().get(id).cloned()+fn to_body(request: &Request) -> serde_json::Value {+ serde_json::to_value(request).expect("a snippets request always serialises")+}++fn from_body<T: DeserializeOwned>(body: serde_json::Value) -> std::result::Result<T, String> {+ serde_json::from_value(body).map_err(|err| format!("an answer that does not read: {err}"))+}++/// Asks the host something on behalf of `window`, and hands the answer, or+/// why there is none, to `apply` on that window alone.+fn ask<T: DeserializeOwned + Send + Sync + 'static>(+ request: Request,+ window: Window,+ apply: impl FnOnce(&mut TermWindow, std::result::Result<T, String>) + Send + Sync + 'static,+) {+ let shared = shared_in_use();+ let deliver = move |answer: std::result::Result<T, String>| {+ promise::spawn::spawn_into_main_thread(async move {+ let repaint = window.clone();+ window.notify(TermWindowNotif::Apply(Box::new(move |term_window| {+ apply(term_window, answer);+ repaint.invalidate();+ })));+ })+ .detach();+ };+ match &shared.session {+ Some(session) => session.call(PLUGIN, to_body(&request), move |answer| {+ deliver(answer.and_then(from_body));+ }),+ None => deliver(Err(shared+ .trouble+ .clone()+ .unwrap_or_else(|| "the plugin host cannot be reached".into()))),+ }+}++/// The rows matching `query`, for `window`'s panel.+pub fn list(+ query: String,+ window: Window,+ apply: impl FnOnce(&mut TermWindow, String, std::result::Result<Vec<Row>, String>)+ + Send+ + Sync+ + 'static,+) {+ let request = Request::List {+ query: query.clone(),+ };+ ask(request, window, move |term_window, rows| {+ apply(term_window, query, rows)+ });+}++/// One snippet whole, for the editor.+pub fn open(+ id: &str,+ window: Window,+ apply: impl FnOnce(&mut TermWindow, Option<Snippet>) + Send + Sync + 'static,+) {+ let request = Request::Get { id: id.to_string() };+ ask(request, window, move |term_window, snippet| match snippet {+ Ok(snippet) => apply(term_window, snippet),+ Err(why) => log::error!("failed to open snippet: {why}"),+ });+}++/// What a pane is sent for a snippet: pasted, or with `run` typed and run.+pub fn text(+ id: &str,+ run: bool,+ window: Window,+ apply: impl FnOnce(&mut TermWindow, String) + Send + Sync + 'static,+) {+ let request = Request::Text {+ id: id.to_string(),+ run,+ };+ ask(request, window, move |term_window, text| match text {+ Ok(Some(text)) => apply(term_window, text),+ Ok(None) => {}+ Err(why) => log::error!("failed to fetch snippet text: {why}"),+ });}-pub fn create_snippet(title: String, body: String) -> Result<SnippetRecord> {- let now = now_ms();- let mut store = SNIPPET_STORE.lock();- let record = store.create(thinkterm_snippets::new_id(now), &title, body, now);- save(&store)?;- Ok(record)+/// Saves what an editor holds, a new snippet when `id` is `None`. The+/// answer, or why there is none, goes to `apply`.+pub fn save(+ id: Option<String>,+ title: String,+ body: String,+ window: Window,+ apply: impl FnOnce(&mut TermWindow, std::result::Result<Saved, String>) + Send + Sync + 'static,+) {+ ask(Request::Save { id, title, body }, window, apply);}-pub fn update_snippet(id: &str, title: String, body: String) -> Result<Option<SnippetRecord>> {- let mut store = SNIPPET_STORE.lock();- let Some(record) = store.update(id, &title, body, now_ms()) else {- return Ok(None);+pub fn delete(id: &str) {+ let shared = shared_in_use();+ let Some(session) = &shared.session else {+ log::error!("failed to delete snippet {id}: the plugin host cannot be reached");+ return;};- save(&store)?;- Ok(Some(record))+ let request = Request::Delete { id: id.to_string() };+ let id = id.to_string();+ session.call(PLUGIN, to_body(&request), move |answer| {+ if let Err(why) = answer {+ log::error!("failed to delete snippet {id}: {why}");+ }+ });}-pub fn delete_snippet(id: &str) -> Result<bool> {- let mut store = SNIPPET_STORE.lock();- let changed = store.delete(id, now_ms());- if changed {- save(&store)?;+#[cfg(test)]+mod tests {+ #[test]+ fn the_host_keeps_snippets_where_the_backup_looks_for_them() {+ assert_eq!(+ thinkterm_plugin_channel::paths::data_dir().join("snippets.json"),+ super::snippets_store_path()+ );}- Ok(changed)}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex a3216dac..23c01397 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -2851,6 +2851,11 @@ pub struct TermWindow {right_sidebar_snippet_body: TextInputState,right_sidebar_snippet_scroll_offset: f32,right_sidebar_snippet_scrollbar_visible_until: Option<Instant>,+ /// This window's view of the snippets: the rows the plugin host sent+ /// for its search, and when to ask again.+ right_sidebar_snippet_listing: thinkterm_snippets::view::Listing,+ /// A save from this window's editor is on its way.+ right_sidebar_snippet_saving: bool,right_sidebar_note: crate::markdown_editor::NoteHostState,right_sidebar_note_view: RightSidebarNoteView,right_sidebar_note_vault_index_root: Option<PathBuf>,@@ -4388,6 +4393,8 @@ impl TermWindow {right_sidebar_snippet_body: TextInputState::new(),right_sidebar_snippet_scroll_offset: 0.0,right_sidebar_snippet_scrollbar_visible_until: None,+ right_sidebar_snippet_listing: Default::default(),+ right_sidebar_snippet_saving: false,right_sidebar_note: crate::markdown_editor::NoteHostState::default(),right_sidebar_note_view: RightSidebarNoteView::Editor,right_sidebar_note_vault_index_root: None,diff --git a/wezterm-gui/src/termwindow/ui/right_sidebar.rs b/wezterm-gui/src/termwindow/ui/right_sidebar.rsindex e27f2415..295a8db0 100644--- a/wezterm-gui/src/termwindow/ui/right_sidebar.rs+++ b/wezterm-gui/src/termwindow/ui/right_sidebar.rs@@ -344,6 +344,9 @@ const FILE_INDEX_ENTRY_LIMIT: usize = thinkterm_file_index::ENTRY_LIMIT;// buffers are released. Reopening within this window keeps everything resident.const FILE_INDEX_IDLE_RELEASE_SECS: u64 = 30;const NOTE_IDLE_RELEASE_SECS: u64 = 30;+/// How long a snippet's Run or Paste waits for its text: a command that+/// arrives later than this is not the one the press was for.+const SNIPPET_SEND_WAIT: Duration = Duration::from_secs(3);// How often the Files panel re-scans the tree while it's visible + focused.const FILE_INDEX_RESCAN_SECS: u64 = 90;// Max number of (root, project) view-state snapshots kept in memory.@@ -2379,10 +2382,19 @@ impl crate::TermWindow {self.right_sidebar_snippet_focus = Some(RightSidebarSnippetField::Title);}+ /// Opens the editor on a snippet once the plugin host has sent it.pub(crate) fn open_existing_snippet_editor(&mut self, id: &str) {- let Some(snippet) = crate::snippets::get_snippet(id) else {+ let Some(window) = self.window.clone() else {return;};+ crate::snippets::open(id, window, |term_window, snippet| {+ if let Some(snippet) = snippet {+ term_window.show_snippet_editor(snippet);+ }+ });+ }++ fn show_snippet_editor(&mut self, snippet: crate::snippets::Snippet) {if self.right_sidebar_mode == RightSidebarMode::Tasks {self.clear_right_sidebar_text_focus();self.schedule_right_sidebar_note_memory_release();@@ -2403,35 +2415,100 @@ impl crate::TermWindow {self.right_sidebar_snippet_body.clear();}+ /// Hands what the editor holds to the plugin host, which decides what+ /// comes of it; the editor follows its answer.pub(crate) fn save_snippet_editor(&mut self) {- let body = self.right_sidebar_snippet_body.text().trim().to_string();- if body.is_empty() {- self.right_sidebar_snippet_focus = Some(RightSidebarSnippetField::Body);+ let editing = self.right_sidebar_snippet_view.clone();+ let id = match &editing {+ RightSidebarSnippetView::List => return,+ RightSidebarSnippetView::EditNew => None,+ RightSidebarSnippetView::EditExisting(id) => Some(id.clone()),+ };+ // A second press waits for the first one's answer rather than+ // saving a new snippet twice.+ if self.right_sidebar_snippet_saving {return;}- let title = self.right_sidebar_snippet_title.text().trim().to_string();- let result = match self.right_sidebar_snippet_view.clone() {- RightSidebarSnippetView::List => return,- RightSidebarSnippetView::EditNew => {- crate::snippets::create_snippet(title, body).map(Some)+ let Some(window) = self.window.clone() else {+ return;+ };+ self.right_sidebar_snippet_saving = true;+ let title = self.right_sidebar_snippet_title.text().to_string();+ let body = self.right_sidebar_snippet_body.text().to_string();+ crate::snippets::save(id, title, body, window, move |term_window, saved| {+ term_window.right_sidebar_snippet_saving = false;+ // The editor moved on meanwhile: the answer is not for it.+ if term_window.right_sidebar_snippet_view != editing {+ return;}- RightSidebarSnippetView::EditExisting(id) => {- crate::snippets::update_snippet(&id, title, body)+ match saved {+ Ok(crate::snippets::Saved::Saved { .. }) => term_window.close_snippet_editor(),+ Ok(crate::snippets::Saved::Empty) => {+ term_window.right_sidebar_snippet_focus = Some(RightSidebarSnippetField::Body);+ }+ // Deleted meanwhile: what was typed is kept, as a new one.+ Ok(crate::snippets::Saved::Gone) => {+ term_window.right_sidebar_snippet_view = RightSidebarSnippetView::EditNew;+ }+ // What was typed stays in the editor.+ Err(why) => log::error!("failed to save snippet: {why}"),}+ });+ }++ /// The rows the Snippets panel shows for this window's search, as the+ /// plugin host last sent them. A search it has not answered is asked+ /// about, one request at a time (thinkterm-snippets `view`).+ fn snippet_rows(&mut self) -> Vec<crate::snippets::Row> {+ let Some(window) = self.window.clone() else {+ return Vec::new();};- match result {- Ok(Some(_)) => self.close_snippet_editor(),- Ok(None) => {- self.right_sidebar_snippet_view = RightSidebarSnippetView::EditNew;- }- Err(err) => log::error!("failed to save snippet: {err:#}"),+ crate::snippets::in_use(&window);+ let query = self.right_sidebar_snippet_search.text();+ let listing = &mut self.right_sidebar_snippet_listing;+ listing.set_query(&query);+ if let Some(query) = listing.next() {+ crate::snippets::list(query, window, |term_window, query, rows| {+ term_window.snippets_listed(query, rows);+ });}+ listing.rows().map(<[_]>::to_vec).unwrap_or_default()}- pub(crate) fn delete_snippet(&mut self, id: &str) {- if let Err(err) = crate::snippets::delete_snippet(id) {- log::error!("failed to delete snippet {id}: {err:#}");+ fn snippets_listed(+ &mut self,+ query: String,+ rows: std::result::Result<Vec<crate::snippets::Row>, String>,+ ) {+ if let Err(why) = self.right_sidebar_snippet_listing.answered(query, rows) {+ log::warn!("snippets: {why}");}+ }++ /// The snippets changed, or the plugin host is back: this window's+ /// rows are asked for again.+ pub(crate) fn snippets_changed(&mut self) {+ self.right_sidebar_snippet_listing.changed();+ }++ /// The session with the plugin host was let go, and this window's rows+ /// with it.+ pub(crate) fn snippets_released(&mut self) {+ self.right_sidebar_snippet_listing.clear();+ }++ fn snippet_availability(&self) -> crate::snippets::Availability {+ if self.right_sidebar_snippet_listing.rows().is_some() {+ return crate::snippets::Availability::Ready;+ }+ match crate::snippets::trouble() {+ Some(why) => crate::snippets::Availability::Unavailable(why),+ None => crate::snippets::Availability::Loading,+ }+ }++ pub(crate) fn delete_snippet(&mut self, id: &str) {+ crate::snippets::delete(id);if matches!(self.right_sidebar_snippet_view,RightSidebarSnippetView::EditExisting(ref editing_id) if editing_id == id@@ -4151,23 +4228,34 @@ impl crate::TermWindow {self.invalidate_window();}+ /// Puts a snippet into the active pane: the plugin host says what to+ /// send, pasted or, with `run`, typed and run. Into the pane active at+ /// the press, never whichever is active when the answer comes, and not+ /// at all once that pane is gone or the answer comes too late to still+ /// be what was meant.pub(crate) fn paste_snippet_to_active_pane(&mut self, id: &str, run: bool) {- let Some(snippet) = crate::snippets::get_snippet(id) else {- return;- };- let Some(pane) = self.get_active_pane_or_overlay() else {+ let (Some(window), Some(pane)) = (self.window.clone(), self.get_active_pane_or_overlay())+ else {return;};- if run {- let Some(buffer) = snippet_run_buffer(&snippet.body) else {+ let pressed = Instant::now();+ let id = id.to_string();+ crate::snippets::text(&id.clone(), run, window, move |_term_window, text| {+ if pane.is_dead() {return;- };- if let Err(err) = pane.writer().write_all(&buffer) {- log::error!("failed to run snippet {id}: {err:#}");}- } else if let Err(err) = pane.send_paste(&snippet.body) {- log::error!("failed to paste snippet {id}: {err:#}");- }+ if pressed.elapsed() > SNIPPET_SEND_WAIT {+ log::warn!("not sending snippet {id}: its text came too late");+ return;+ }+ if run {+ if let Err(err) = pane.writer().write_all(text.as_bytes()) {+ log::error!("failed to run snippet {id}: {err:#}");+ }+ } else if let Err(err) = pane.send_paste(&text) {+ log::error!("failed to paste snippet {id}: {err:#}");+ }+ });}pub(crate) fn copy_right_sidebar_focused_input(&self, destination: ClipboardCopyDestination) {@@ -6922,7 +7010,9 @@ impl crate::TermWindow {}fn filtered_snippet_count(&self) -> usize {- crate::snippets::matching_snippet_count(&self.right_sidebar_snippet_search.text())+ self.right_sidebar_snippet_listing+ .rows()+ .map_or(0, <[_]>::len)}pub fn paint_right_sidebar(@@ -17235,7 +17325,7 @@ impl crate::TermWindow {+ self.ui_px(SNIPPET_LIST_TOP_GAP);let query = self.right_sidebar_snippet_search.text();let searching = !query.trim().is_empty();- let snippets = crate::snippets::matching_snippets(&query);+ let snippets = self.snippet_rows();let row_height = self.ui_px(SNIPPET_CARD_HEIGHT) + self.ui_px(SNIPPET_ROW_GAP);// The panel's bottom padding, which doubles as the mask that keeps// cards out of it; whatever overshoots it is cut by the window edge.@@ -17250,10 +17340,13 @@ impl crate::TermWindow {let scroll_offset = self.right_sidebar_snippet_scroll_offset;if snippets.is_empty() {+ let availability = self.snippet_availability();let empty_height = self.ui_px(RIGHT_SIDEBAR_EMPTY_HEIGHT).min(content_bottom.saturating_sub(list_top + self.ui_px(SIDEBAR_INSET)));- if empty_height == 0 {+ // Still on their way from the plugin host, usually for a frame+ // or two: saying there are none would be wrong, so say nothing.+ if empty_height == 0 || availability == crate::snippets::Availability::Loading {// No room for the empty-state card, but the toolbar must// still paint: it holds the search box, and losing it here// would leave a non-matching filter impossible to clear.@@ -17298,10 +17391,12 @@ impl crate::TermWindow {empty_icon_size,muted_fg,)?;- let empty_label = if !searching {- crate::i18n::tr("right-no-snippets")- } else {- crate::i18n::tr("right-no-matching-snippets")+ let empty_label = match availability {+ crate::snippets::Availability::Unavailable(_) => {+ crate::i18n::tr("right-snippets-unavailable")+ }+ _ if !searching => crate::i18n::tr("right-no-snippets"),+ _ => crate::i18n::tr("right-no-matching-snippets"),};self.paint_sidebar_text(layers,@@ -17638,7 +17733,7 @@ impl crate::TermWindow {x: usize,y: usize,width: usize,- snippet: &crate::snippets::SnippetRecord,+ snippet: &crate::snippets::Row,clip_top: usize,clip_bottom: usize,// Bounds of the two opaque scroll masks. Text is a quad the sidebar@@ -17723,14 +17818,13 @@ impl crate::TermWindow {foreground,)?;}- let preview = snippet_preview(&snippet.body);let preview_y = y + self.ui_px(SIDEBAR_INSET) * 2 + cell_height + 8;if visible(preview_y, cell_height) {self.paint_sidebar_text(layers,ui_font,ui_metrics,- &preview,+ &snippet.preview,text_x,preview_y,width.saturating_sub(card_pad * 2),@@ -20755,31 +20849,6 @@ fn remote_file_icon(row: &RemoteFileRow) -> RightSidebarFileIcon {RightSidebarFileIcon::Svg(icon)}-fn snippet_preview(body: &str) -> String {- body.lines()- .find_map(|line| {- let trimmed = line.trim();- (!trimmed.is_empty()).then_some(trimmed)- })- .unwrap_or("")- .chars()- .take(96)- .collect()-}--fn snippet_run_buffer(body: &str) -> Option<Vec<u8>> {- let normalized = body.replace("\r\n", "\n").replace('\r', "\n");- let lines: Vec<_> = normalized.split('\n').collect();- let start = lines.iter().position(|line| !line.trim().is_empty())?;- let end = lines.iter().rposition(|line| !line.trim().is_empty())?;- let trimmed = lines[start..=end].join("\n");-- let mut buffer = String::with_capacity(trimmed.len() + 1);- buffer.push_str(&trimmed);- buffer.push('\n');- Some(buffer.replace('\n', "\r").into_bytes())-}-/// Wrap a filesystem path to a width, breaking after separators.////// The generic wrapper breaks wherever the width runs out, which cuts a@@ -21054,12 +21123,11 @@ mod tests {right_sidebar_file_browse_rows_from_dir_cache, right_sidebar_file_row_metrics,right_sidebar_open_with_cache_key, sanitize_preview_text, scrollable_note_table_columns,search_right_sidebar_file_index, sidebar_message_layout, sidebar_row_element_visible,- snippet_cursor_visible, snippet_run_buffer, sorted_open_with_candidates,- spawn_pasted_image_staging, stage_pasted_image, terminal_paste_snapshot_mismatch,- virtual_note_line_range, visible_code_block_rounded_edges, visible_file_row_range,- wrap_snippet_text_for_width, FileReleaseAction, FileRowPlacement,- NoteApproximateTextMetrics, NoteCodeHighlightEntry, NoteCodeHighlightState,- NoteReleaseAction, NoteVaultProblem, RemoteLeaseFailureDisposition,+ snippet_cursor_visible, sorted_open_with_candidates, spawn_pasted_image_staging,+ stage_pasted_image, terminal_paste_snapshot_mismatch, virtual_note_line_range,+ visible_code_block_rounded_edges, visible_file_row_range, wrap_snippet_text_for_width,+ FileReleaseAction, FileRowPlacement, NoteApproximateTextMetrics, NoteCodeHighlightEntry,+ NoteCodeHighlightState, NoteReleaseAction, NoteVaultProblem, RemoteLeaseFailureDisposition,TerminalPasteSnapshotMismatch, TerminalPasteTarget, FILE_PREVIEW_MAX_BYTES,LOCAL_COPY_CHUNK, NOTE_CODE_BLOCK_RADIUS, NOTE_CODE_HEADER_HEIGHT,};@@ -23168,29 +23236,6 @@ mod tests {assert_eq!(preview_text_range("ab你好cd", 4, 99), "cd");}- #[test]- fn snippet_run_buffer_appends_single_enter() {- assert_eq!(- snippet_run_buffer("sudo apt update").unwrap(),- b"sudo apt update\r"- );- }-- #[test]- fn snippet_run_buffer_trims_outer_blank_lines() {- assert_eq!(snippet_run_buffer("\n\ncmd\r\n").unwrap(), b"cmd\r");- }-- #[test]- fn snippet_run_buffer_preserves_internal_script_lines() {- assert_eq!(snippet_run_buffer("one\ntwo").unwrap(), b"one\rtwo\r");- }-- #[test]- fn snippet_run_buffer_ignores_blank_body() {- assert!(snippet_run_buffer("\n \r\n\t").is_none());- }-#[test]fn wrap_snippet_text_wraps_at_word_boundaries() {let lines = wrap_snippet_text_for_width("sudo apt update", 8, false, |s| {