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(gui): ask before pastes and links, sort alerts, add Permissions
RoversXff04045d3de5
diff --git a/thinkterm-i18n/i18n/de-DE.ftl b/thinkterm-i18n/i18n/de-DE.ftlindex d5fba940..e9c11b6d 100644--- a/thinkterm-i18n/i18n/de-DE.ftl+++ b/thinkterm-i18n/i18n/de-DE.ftl@@ -1740,6 +1740,7 @@ share-pill-removed = { $owner } hat Sie entfernt · Schließenshare-pill-expired = Die Freigabe ist abgelaufen · Schließenshare-pill-closed = Das geteilte Terminal wurde geschlossen · Schließensettings-section-share-sync = Teilen & Synchronisieren+settings-section-privacy = Berechtigungensettings-share-sync-description = Lassen Sie andere Konten auf diesem Rechner Ihren Terminals zusehen.settings-sharing = Terminals teilensettings-sharing-description = Eingeschaltet haben Terminals einen Teilen-Knopf, und die Seitenleiste zeigt, was andere mit Ihnen teilen. Andere sehen nur zu; zum Tippen fragen sie an, und Sie entscheiden. Ausschalten beendet Ihre laufenden Freigaben.@@ -1748,3 +1749,43 @@ settings-sharing-experimental = Diese Funktion ist experimentell: Sie wird viellsettings-status-sharing-on = Teilen eingeschaltetsettings-status-sharing-off = Teilen ausgeschaltetsettings-status-sharing-error = Die Einstellung zum Teilen konnte nicht gespeichert werden: { $error }++## Asking before something a terminal program printed is acted on.+link-open-other-app = In anderer App öffnen+link-open-cancel = Abbrechen+link-refused-unsafe = Nicht geöffnet: Der Link ist unsicher+paste-confirm-header = Der Text enthält Zeilenumbrüche und könnte beim Einfügen sofort Befehle ausführen+paste-confirm-anyway = Trotzdem einfügen+paste-confirm-cancel = Abbrechen+settings-paste-confirmation = Vor dem Einfügen von Zeilenumbrüchen fragen+settings-paste-confirmation-description = Fragt nach, bevor Text mit Zeilenumbrüchen in ein Programm geht, das jede Zeile sofort ausführen würde. Shells wie zsh, die Eingefügtes als Ganzes annehmen, sind nicht betroffen.++## Settings › Workspaces › Notifications: which moments each prompt answers.+settings-dock-badge = Zahl am Dock-Symbol+settings-dock-badge-description = Zeigt am Dock-Symbol von ThinkTerm, wie viele Threads etwas haben, das Sie noch nicht angesehen haben.+settings-work-moment-finished = Fertig+settings-work-moment-needs-input = Braucht Sie+settings-work-moment-error = Fehler++## Settings › General: what macOS lets programs in local terminals do.+settings-privacy-page-description = macOS rechnet jedes Programm in den Terminals von ThinkTerm ThinkTerm zu: Eine hier erlaubte Berechtigung kann jedes davon nutzen.+settings-privacy-heading = Berechtigungen für Programme in Terminals+settings-privacy-full-disk = Festplattenvollzugriff+settings-privacy-full-disk-description = Lesen und Schreiben an geschützten Orten wie Schreibtisch, Dokumente, Downloads und Mail.+settings-privacy-full-disk-caution = Vorsicht: Einmal erlaubt, kann jedes Programm in einem Terminal, auch Kommandozeilenwerkzeuge, Skripte und KI-Agenten, diese Orte und die Daten anderer Apps lesen und ändern, ohne dass macOS Sie fragt. Schalten Sie ihn nur ein, wenn Sie ihn brauchen, und danach in den Systemeinstellungen wieder aus.+settings-privacy-screen = Bildschirm- und System-Audioaufnahme+settings-privacy-screen-description = Für Programme, die Bildschirmfotos machen, den Bildschirm oder den Systemton aufnehmen.+settings-privacy-microphone = Mikrofon+settings-privacy-microphone-description = Für Programme, die Ton aufnehmen oder Spracheingabe nutzen. macOS fragt, wenn eines es zum ersten Mal braucht.+settings-privacy-camera = Kamera+settings-privacy-camera-description = Für Programme, die Fotos oder Videos aufnehmen. macOS fragt, wenn eines es zum ersten Mal braucht.+settings-privacy-open = Systemeinstellungen öffnen+settings-privacy-granted = Erlaubt+settings-privacy-not-granted = Nicht erlaubt+settings-privacy-denied = Abgelehnt+settings-privacy-not-asked = Noch nicht gefragt+settings-privacy-unknown = Unbekannt+settings-privacy-checking = Wird geprüft…+settings-privacy-holder-server = ThinkTerm-Hintergrunddienst+settings-privacy-holder-app = ThinkTerm+settings-privacy-holder-description = Diese Berechtigungen gelten unter seinem Namen. Festplattenvollzugriff muss von Hand hinzugefügt werden: in den Systemeinstellungen auf + klicken und ihn in die Liste ziehen.diff --git a/thinkterm-i18n/i18n/en-US.ftl b/thinkterm-i18n/i18n/en-US.ftlindex 21559b41..f678edd8 100644--- a/thinkterm-i18n/i18n/en-US.ftl+++ b/thinkterm-i18n/i18n/en-US.ftl@@ -1740,6 +1740,7 @@ share-pill-removed = { $owner } removed you · Closeshare-pill-expired = The share ran out · Closeshare-pill-closed = The shared terminal closed · Closesettings-section-share-sync = Share & Sync+settings-section-privacy = Permissionssettings-share-sync-description = Let other accounts on this machine watch your terminals.settings-sharing = Share terminalssettings-sharing-description = When on, terminals have a share button, and the sidebar lists what others share with you. Others can only watch; to type, they ask and you decide. Turning it off stops what you share.@@ -1748,3 +1749,43 @@ settings-sharing-experimental = This is an experimental feature: it may be removsettings-status-sharing-on = Sharing turned onsettings-status-sharing-off = Sharing turned offsettings-status-sharing-error = Could not save the sharing setting: { $error }++## Asking before something a terminal program printed is acted on.+link-open-other-app = Open in Another App+link-open-cancel = Cancel+link-refused-unsafe = Not Opened: the Link Is Unsafe+paste-confirm-header = This text has line breaks and could run commands as soon as it is pasted+paste-confirm-anyway = Paste Anyway+paste-confirm-cancel = Cancel+settings-paste-confirmation = Ask before pasting line breaks+settings-paste-confirmation-description = Before text with line breaks goes into a program that would run each line as it arrives, ask first. Shells that take a paste as one block, such as zsh, are not asked about.++## Settings › Workspaces › Notifications: which moments each prompt answers.+settings-dock-badge = Dock Icon Count+settings-dock-badge-description = Show on ThinkTerm's Dock icon how many threads have something you haven't looked at yet.+settings-work-moment-finished = Finished+settings-work-moment-needs-input = Needs You+settings-work-moment-error = Error++## Settings › General: what macOS lets programs in local terminals do.+settings-privacy-page-description = macOS counts every program run in ThinkTerm's terminals as ThinkTerm: a permission allowed here is one each of them can use.+settings-privacy-heading = Permissions for Programs in Terminals+settings-privacy-full-disk = Full Disk Access+settings-privacy-full-disk-description = Read and write protected places such as Desktop, Documents, Downloads and Mail.+settings-privacy-full-disk-caution = Caution: once allowed, any program in a terminal, scripts and AI agents included, can read and write these places and other apps' data without macOS asking. Turn it on only when you need it, and off again in System Settings when done.+settings-privacy-screen = Screen & System Audio Recording+settings-privacy-screen-description = For programs that take screenshots, record the screen or record system audio.+settings-privacy-microphone = Microphone+settings-privacy-microphone-description = For programs that record sound or take voice input. macOS asks the first time one does.+settings-privacy-camera = Camera+settings-privacy-camera-description = For programs that take photos or video. macOS asks the first time one does.+settings-privacy-open = Open System Settings+settings-privacy-granted = Allowed+settings-privacy-not-granted = Not allowed+settings-privacy-denied = Denied+settings-privacy-not-asked = Not asked yet+settings-privacy-unknown = Unknown+settings-privacy-checking = Checking…+settings-privacy-holder-server = ThinkTerm Background Service+settings-privacy-holder-app = ThinkTerm+settings-privacy-holder-description = These permissions are kept under its name. Full Disk Access has to be added by hand: click + in System Settings and drag it into the list.diff --git a/thinkterm-i18n/i18n/fr-FR.ftl b/thinkterm-i18n/i18n/fr-FR.ftlindex 1d1a330c..a63ee245 100644--- a/thinkterm-i18n/i18n/fr-FR.ftl+++ b/thinkterm-i18n/i18n/fr-FR.ftl@@ -1734,6 +1734,7 @@ share-pill-removed = { $owner } vous a retiré · Fermershare-pill-expired = Le partage a expiré · Fermershare-pill-closed = Le terminal partagé s'est fermé · Fermersettings-section-share-sync = Partage et synchronisation+settings-section-privacy = Autorisationssettings-share-sync-description = Laissez d'autres comptes de cette machine regarder vos terminaux.settings-sharing = Partager les terminauxsettings-sharing-description = Activé, les terminaux ont un bouton de partage et la barre latérale liste ce que d'autres partagent avec vous. Les autres ne font que regarder ; pour taper, ils le demandent et vous décidez. Le désactiver arrête vos partages en cours.@@ -1742,3 +1743,43 @@ settings-sharing-experimental = Cette fonction est expérimentale : elle pourrasettings-status-sharing-on = Partage activésettings-status-sharing-off = Partage désactivésettings-status-sharing-error = Impossible d'enregistrer le réglage de partage : { $error }++## Asking before something a terminal program printed is acted on.+link-open-other-app = Ouvrir dans une autre app+link-open-cancel = Annuler+link-refused-unsafe = Non ouvert : le lien est dangereux+paste-confirm-header = Ce texte contient des retours à la ligne et pourrait lancer des commandes dès qu'il est collé+paste-confirm-anyway = Coller quand même+paste-confirm-cancel = Annuler+settings-paste-confirmation = Demander avant de coller des retours à la ligne+settings-paste-confirmation-description = Demande avant de coller du texte avec des retours à la ligne dans un programme qui exécuterait chaque ligne aussitôt. Les shells comme zsh, qui reçoivent un collage d'un seul bloc, ne sont pas concernés.++## Settings › Workspaces › Notifications: which moments each prompt answers.+settings-dock-badge = Nombre sur l'icône du Dock+settings-dock-badge-description = Afficher sur l'icône de ThinkTerm dans le Dock combien de sessions ont du nouveau que vous n'avez pas encore vu.+settings-work-moment-finished = Terminé+settings-work-moment-needs-input = Vous attend+settings-work-moment-error = Erreur++## Settings › General: what macOS lets programs in local terminals do.+settings-privacy-page-description = macOS compte chaque programme lancé dans les terminaux de ThinkTerm comme ThinkTerm : une autorisation accordée ici, chacun d'eux peut s'en servir.+settings-privacy-heading = Autorisations des programmes dans les terminaux+settings-privacy-full-disk = Accès complet au disque+settings-privacy-full-disk-description = Lire et écrire dans des emplacements protégés comme le Bureau, Documents, Téléchargements et Mail.+settings-privacy-full-disk-caution = Attention : une fois autorisé, tout programme lancé dans un terminal, outils en ligne de commande, scripts et agents IA compris, peut lire et modifier ces emplacements et les données des autres apps sans que macOS vous le demande. Ne l'activez que si vous en avez besoin, et désactivez-le ensuite dans Réglages Système.+settings-privacy-screen = Enregistrement de l'écran et de l'audio du système+settings-privacy-screen-description = Pour les programmes qui font des captures d'écran ou enregistrent l'écran ou le son du système.+settings-privacy-microphone = Micro+settings-privacy-microphone-description = Pour les programmes qui enregistrent du son ou utilisent la saisie vocale. macOS demande la première fois qu'un programme en a besoin.+settings-privacy-camera = Caméra+settings-privacy-camera-description = Pour les programmes qui prennent des photos ou des vidéos. macOS demande la première fois qu'un programme en a besoin.+settings-privacy-open = Ouvrir Réglages Système+settings-privacy-granted = Autorisé+settings-privacy-not-granted = Non autorisé+settings-privacy-denied = Refusé+settings-privacy-not-asked = Pas encore demandé+settings-privacy-unknown = Inconnu+settings-privacy-checking = Vérification…+settings-privacy-holder-server = Service d'arrière-plan de ThinkTerm+settings-privacy-holder-app = ThinkTerm+settings-privacy-holder-description = Ces autorisations sont enregistrées à son nom. L'accès complet au disque s'ajoute à la main : cliquez sur + dans Réglages Système et faites-le glisser dans la liste.diff --git a/thinkterm-i18n/i18n/ja-JP.ftl b/thinkterm-i18n/i18n/ja-JP.ftlindex 91cb9dbe..0fe32fe6 100644--- a/thinkterm-i18n/i18n/ja-JP.ftl+++ b/thinkterm-i18n/i18n/ja-JP.ftl@@ -1694,6 +1694,7 @@ share-pill-removed = { $owner } さんに外されました · 閉じるshare-pill-expired = 共有の時間が終わりました · 閉じるshare-pill-closed = 共有されていたターミナルが閉じました · 閉じるsettings-section-share-sync = 共有と同期+settings-section-privacy = 権限settings-share-sync-description = このマシンの他のアカウントにターミナルを見せます。settings-sharing = ターミナルを共有settings-sharing-description = オンにすると、ターミナルに共有ボタンが付き、サイドバーに共有されたターミナルが表示されます。相手は見るだけで、入力するには申請してあなたが許可します。オフにすると共有中のものは止まります。@@ -1702,3 +1703,43 @@ settings-sharing-experimental = 試験中の機能です。今後なくなる可settings-status-sharing-on = 共有をオンにしましたsettings-status-sharing-off = 共有をオフにしましたsettings-status-sharing-error = 共有の設定を保存できませんでした:{ $error }++## Asking before something a terminal program printed is acted on.+link-open-other-app = 別のアプリで開く+link-open-cancel = キャンセル+link-refused-unsafe = 開きませんでした:安全でないリンクです+paste-confirm-header = 改行を含むため、貼り付けるとすぐにコマンドが実行されるおそれがあります+paste-confirm-anyway = それでも貼り付ける+paste-confirm-cancel = キャンセル+settings-paste-confirmation = 改行を含む貼り付けの前に確認+settings-paste-confirmation-description = 改行を含む内容を、1 行ずつすぐ実行してしまうプログラムに貼り付ける前に確認します。zsh のように貼り付けをひとまとまりで受け取るシェルでは確認しません。++## Settings › Workspaces › Notifications: which moments each prompt answers.+settings-dock-badge = Dock アイコンの数字+settings-dock-badge-description = Dock の ThinkTerm アイコンに、まだ見ていないスレッドの数を表示します。+settings-work-moment-finished = 完了+settings-work-moment-needs-input = 対応待ち+settings-work-moment-error = エラー++## Settings › General: what macOS lets programs in local terminals do.+settings-privacy-page-description = macOS は ThinkTerm のターミナルで実行するプログラムをすべて ThinkTerm として扱います。ここで許可した権限は、ターミナル内のどのプログラムも使えます。+settings-privacy-heading = ターミナル内のプログラムの権限+settings-privacy-full-disk = フルディスクアクセス+settings-privacy-full-disk-description = デスクトップ、書類、ダウンロード、メールなど保護された場所の読み書き。+settings-privacy-full-disk-caution = 注意:許可すると、ターミナルで実行するどのプログラムも(コマンドラインツール、スクリプト、AI エージェントを含む)、macOS に確認されることなく、これらの場所や他のアプリのデータを読み書きできます。必要なときだけオンにし、使い終わったらシステム設定でオフにしてください。+settings-privacy-screen = 画面とシステムオーディオの録音+settings-privacy-screen-description = スクリーンショット、画面収録、システム音声の録音をするプログラムに必要です。+settings-privacy-microphone = マイク+settings-privacy-microphone-description = 録音や音声入力をするプログラムに必要です。プログラムが最初に使うときにシステムが確認します。+settings-privacy-camera = カメラ+settings-privacy-camera-description = 写真やビデオを撮るプログラムに必要です。プログラムが最初に使うときにシステムが確認します。+settings-privacy-open = システム設定を開く+settings-privacy-granted = 許可済み+settings-privacy-not-granted = 未許可+settings-privacy-denied = 拒否+settings-privacy-not-asked = 未確認+settings-privacy-unknown = 不明+settings-privacy-checking = 確認中…+settings-privacy-holder-server = ThinkTerm バックグラウンドサービス+settings-privacy-holder-app = ThinkTerm+settings-privacy-holder-description = これらの権限はこのプログラムの名前で記録されます。フルディスクアクセスは手動で追加します:システム設定で + を押し、これをリストにドラッグしてください。diff --git a/thinkterm-i18n/i18n/zh-CN.ftl b/thinkterm-i18n/i18n/zh-CN.ftlindex 564f6ec1..06d58492 100644--- a/thinkterm-i18n/i18n/zh-CN.ftl+++ b/thinkterm-i18n/i18n/zh-CN.ftl@@ -1694,6 +1694,7 @@ share-pill-removed = { $owner } 把你移出了 · 关闭share-pill-expired = 分享到时间了 · 关闭share-pill-closed = 分享的终端已关闭 · 关闭settings-section-share-sync = 共享与同步+settings-section-privacy = 权限settings-share-sync-description = 让这台机器上的其他账户看你的终端。settings-sharing = 分享终端settings-sharing-description = 打开后,终端右上角会有分享按钮,侧栏会列出别人分享给你的终端。对方只能看,要打字得你同意。关掉会停止你正在进行的分享。@@ -1702,3 +1703,43 @@ settings-sharing-experimental = 这是测试中的功能,之后可能会移除settings-status-sharing-on = 已打开分享settings-status-sharing-off = 已关闭分享settings-status-sharing-error = 没能保存分享设置:{ $error }++## Asking before something a terminal program printed is acted on.+link-open-other-app = 用其他应用打开+link-open-cancel = 取消+link-refused-unsafe = 没有打开:链接不安全+paste-confirm-header = 这段内容带换行,一粘贴就可能直接执行命令+paste-confirm-anyway = 仍然粘贴+paste-confirm-cancel = 取消+settings-paste-confirmation = 粘贴带换行的内容前先问+settings-paste-confirmation-description = 带换行的内容要贴进会一行行马上执行的程序时,先问一下。zsh 这类把整段当一次粘贴的 shell 不会问。++## Settings › Workspaces › Notifications: which moments each prompt answers.+settings-dock-badge = Dock 图标数字+settings-dock-badge-description = Dock 上的 ThinkTerm 图标显示有几个 Thread 你还没看。+settings-work-moment-finished = 完成+settings-work-moment-needs-input = 等你+settings-work-moment-error = 出错++## Settings › General: what macOS lets programs in local terminals do.+settings-privacy-page-description = macOS 把 ThinkTerm 终端里运行的程序都算在 ThinkTerm 名下:在这里允许的权限,终端里的每个程序都能用。+settings-privacy-heading = 终端里程序的权限+settings-privacy-full-disk = 完全磁盘访问+settings-privacy-full-disk-description = 读写桌面、文稿、下载、邮件这些受保护的位置。+settings-privacy-full-disk-caution = 注意:允许后,终端里运行的任何程序,包括命令行工具、脚本和 AI agent,都能直接读写这些位置和其他应用的数据,系统不会再问你。只在确实需要时打开,用完可以在系统设置里关掉。+settings-privacy-screen = 屏幕与系统录音+settings-privacy-screen-description = 截屏、录屏、录系统声音的程序要用。+settings-privacy-microphone = 麦克风+settings-privacy-microphone-description = 录音、语音输入的程序要用。程序第一次用时系统会问。+settings-privacy-camera = 摄像头+settings-privacy-camera-description = 拍照、录像的程序要用。程序第一次用时系统会问。+settings-privacy-open = 打开系统设置+settings-privacy-granted = 已允许+settings-privacy-not-granted = 没有+settings-privacy-denied = 被拒绝+settings-privacy-not-asked = 还没问过+settings-privacy-unknown = 查不到+settings-privacy-checking = 正在查…+settings-privacy-holder-server = ThinkTerm 后台服务+settings-privacy-holder-app = ThinkTerm+settings-privacy-holder-description = 这些权限记在它名下。完全磁盘访问要自己加:在系统设置里点 +,把它拖进列表。diff --git a/wezterm-gui/src/main.rs b/wezterm-gui/src/main.rsindex 192f8502..55da2009 100644--- a/wezterm-gui/src/main.rs+++ b/wezterm-gui/src/main.rs@@ -59,6 +59,8 @@ mod overlay;mod page_poll;mod perf;mod plugins;+#[cfg(target_os = "macos")]+mod privacy_status;mod quad;mod renderer_choice;mod renderstate;diff --git a/wezterm-gui/src/native_settings.rs b/wezterm-gui/src/native_settings.rsindex 33111c83..b6838394 100644--- a/wezterm-gui/src/native_settings.rs+++ b/wezterm-gui/src/native_settings.rs@@ -952,6 +952,10 @@ pub(crate) struct NativeTerminalSettings {pub(crate) copy_on_select: bool,#[serde(deserialize_with = "choice_or_default")]pub(crate) right_click: NativeRightClick,+ /// Ask before a paste whose line breaks would run its lines one by one,+ /// in a program that did not ask for pastes bracketed. Off unless chosen.+ #[serde(default)]+ pub(crate) paste_confirmation: bool,#[serde(deserialize_with = "choice_or_default")]pub(crate) copy_effect: NativeCopyEffect,/// The pane the mouse moves onto takes the focus, without a click.@@ -990,6 +994,7 @@ impl Default for NativeTerminalSettings {selection_style: NativeSelectionStyle::default(),copy_on_select: true,right_click: NativeRightClick::default(),+ paste_confirmation: false,copy_effect: NativeCopyEffect::default(),focus_follows_mouse: false,text_contrast: NativeTextContrast::default(),@@ -1034,6 +1039,11 @@ pub(crate) fn right_click() -> NativeRightClick {load_shared().terminal.right_click}+/// Read on every paste with a line break in it, through the shared handle.+pub(crate) fn paste_confirmation() -> bool {+ load_shared().terminal.paste_confirmation+}+/// Read on every copy and paste, through the shared handle.pub(crate) fn copy_effect() -> NativeCopyEffect {load_shared().terminal.copy_effect@@ -1518,6 +1528,14 @@ pub(crate) struct NativeWorkspaceSettings {/// While ThinkTerm is in the background, tell the system when a thread/// finishes, starts waiting on you, or stops on an error.pub(crate) system_notifications_enabled: bool,+ /// Which of a thread's moments the sounds mark, while they are on.+ pub(crate) notification_sound_moments: WorkMoments,+ /// Which of them the system notifications tell of, while they are on.+ pub(crate) system_notification_moments: WorkMoments,+ /// Count the threads with something unseen on the Dock icon (macOS).+ pub(crate) dock_badge_enabled: bool,+ /// Which of their moments the Dock icon counts, while it counts.+ pub(crate) dock_badge_moments: WorkMoments,/// Updating a remote mux server hands its sessions to the new version/// instead of stopping it; off, the update asks whether to stop it.pub(crate) remote_update_keeps_sessions: bool,@@ -1546,6 +1564,10 @@ impl Default for NativeWorkspaceSettings {remote_drop_destination: String::new(),notification_sounds_enabled: true,system_notifications_enabled: true,+ notification_sound_moments: WorkMoments::default(),+ system_notification_moments: WorkMoments::default(),+ dock_badge_enabled: true,+ dock_badge_moments: WorkMoments::default(),remote_update_keeps_sessions: true,update_download_source: thinkterm_update::DownloadSource::Auto.name().to_string(),check_for_updates: None,@@ -1557,6 +1579,59 @@ impl Default for NativeWorkspaceSettings {}}+/// A moment in a thread's work that may prompt you: it finished, it waits+/// on you, or its program stopped on an error.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum WorkMoment {+ Finished,+ NeedsInput,+ Error,+}++impl WorkMoment {+ pub(crate) const ALL: [WorkMoment; 3] =+ [WorkMoment::Finished, WorkMoment::NeedsInput, WorkMoment::Error];+}++/// Which [`WorkMoment`]s one kind of prompt -- the sound, the system+/// notification, the Dock count -- answers. All of them unless taken out.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]+#[serde(default)]+pub(crate) struct WorkMoments {+ pub(crate) finished: bool,+ pub(crate) needs_input: bool,+ pub(crate) error: bool,+}++impl Default for WorkMoments {+ fn default() -> Self {+ Self {+ finished: true,+ needs_input: true,+ error: true,+ }+ }+}++impl WorkMoments {+ pub(crate) fn includes(self, moment: WorkMoment) -> bool {+ match moment {+ WorkMoment::Finished => self.finished,+ WorkMoment::NeedsInput => self.needs_input,+ WorkMoment::Error => self.error,+ }+ }++ pub(crate) fn toggle(&mut self, moment: WorkMoment) {+ let slot = match moment {+ WorkMoment::Finished => &mut self.finished,+ WorkMoment::NeedsInput => &mut self.needs_input,+ WorkMoment::Error => &mut self.error,+ };+ *slot = !*slot;+ }+}+/// Application-wide UI localization. `None` identifies a pre-localization/// settings file so the effective preference can be migrated from the legacy/// Onboarding-only value without mutating Onboarding itself.@@ -3133,14 +3208,35 @@ pub(crate) fn pane_header_font_size(settings: &ThinkTermNativeSettings) -> f64 {.clamp(10.0, 28.0)}-pub(crate) fn notification_sounds_enabled() -> bool {- load().workspaces.notification_sounds_enabled-}-pub(crate) fn system_notifications_enabled() -> bool {load_shared().workspaces.system_notifications_enabled}+/// Whether a sound marks `moment`: sounds are on, and on for it.+pub(crate) fn notification_sound_for(moment: WorkMoment) -> bool {+ let settings = load_shared();+ settings.workspaces.notification_sounds_enabled+ && settings.workspaces.notification_sound_moments.includes(moment)+}++/// Whether the system is told of `moment`, as for the sounds.+pub(crate) fn system_notification_for(moment: WorkMoment) -> bool {+ system_notifications_enabled()+ && load_shared()+ .workspaces+ .system_notification_moments+ .includes(moment)+}++/// The moments the Dock icon counts, or `None` while it counts nothing.+pub(crate) fn dock_badge_moments() -> Option<WorkMoments> {+ let settings = load_shared();+ settings+ .workspaces+ .dock_badge_enabled+ .then_some(settings.workspaces.dock_badge_moments)+}+/// What is shown of programs' own status reports. `load_shared`: asked/// while painting.pub(crate) fn agent_status_display() -> NativeAgentStatusDisplay {@@ -3248,6 +3344,35 @@ pub(crate) fn main_window_renderer(mod tests {use super::*;+ #[test]+ fn every_moment_prompts_until_one_is_taken_out() {+ // A settings file from before the moments: as it behaved, and the+ // Dock counts.+ let settings: ThinkTermNativeSettings = serde_json::from_str("{}").unwrap();+ let workspaces = &settings.workspaces;+ for moment in WorkMoment::ALL {+ assert!(workspaces.notification_sound_moments.includes(moment));+ assert!(workspaces.system_notification_moments.includes(moment));+ assert!(workspaces.dock_badge_moments.includes(moment));+ }+ assert!(workspaces.dock_badge_enabled);++ let settings: ThinkTermNativeSettings = serde_json::from_str(+ r#"{"workspaces": {"notification_sound_moments": {"finished": false}}}"#,+ )+ .unwrap();+ let moments = settings.workspaces.notification_sound_moments;+ assert!(!moments.includes(WorkMoment::Finished));+ assert!(moments.includes(WorkMoment::NeedsInput));+ assert!(moments.includes(WorkMoment::Error));++ let mut moments = WorkMoments::default();+ moments.toggle(WorkMoment::Error);+ assert!(!moments.includes(WorkMoment::Error));+ moments.toggle(WorkMoment::Error);+ assert_eq!(moments, WorkMoments::default());+ }+#[test]fn sharing_is_off_until_turned_on() {let settings: ThinkTermNativeSettings = serde_json::from_str("{}").unwrap();@@ -3760,15 +3885,16 @@ mod tests {assert_eq!(settings.terminal.scroll_mode, NativeScrollMode::Stepped);assert_eq!(settings.localization.language.as_deref(), Some("ja-JP"));- // Selecting copies unless turned off; the focus waits for a click- // unless turned on.+ // Selecting copies unless turned off; the focus waits for a click,+ // and a paste goes in without asking, unless turned on.assert!(settings.terminal.copy_on_select);assert!(!settings.terminal.focus_follows_mouse);+ assert!(!settings.terminal.paste_confirmation);// The ones this build knows still read as written.let json = r#"{ "version": 1, "terminal": {"selection_style": "square", "copy_on_select": false, "right_click": "copy_or_paste",- "copy_effect": "color", "focus_follows_mouse": true+ "copy_effect": "color", "focus_follows_mouse": true, "paste_confirmation": true} }"#;let settings: ThinkTermNativeSettings = serde_json::from_str(json).unwrap();assert!(!settings.terminal.copy_on_select);@@ -3776,6 +3902,7 @@ mod tests {assert_eq!(settings.terminal.right_click, NativeRightClick::CopyOrPaste);assert_eq!(settings.terminal.copy_effect, NativeCopyEffect::Color);assert!(settings.terminal.focus_follows_mouse);+ assert!(settings.terminal.paste_confirmation);}/// The four this build does know still round-trip.diff --git a/wezterm-gui/src/privacy_status.rs b/wezterm-gui/src/privacy_status.rsnew file mode 100644index 00000000..f72ff7da--- /dev/null+++ b/wezterm-gui/src/privacy_status.rs@@ -0,0 +1,224 @@+//! The macOS privacy permissions the programs in local terminals get, for+//! Settings › General. macOS holds whoever spawned a terminal's shell+//! responsible for it: this app when local terminals run in it, else the+//! session server, which is responsible for itself and answers for itself+//! (`wezterm_mux_server_impl::privacy`).++use anyhow::Context;+use smol::process::Command;+use std::path::PathBuf;+use std::process::Stdio;+use std::sync::{mpsc, Mutex};+use std::time::{Duration, Instant};+use wezterm_mux_server_impl::privacy::{self, PrivacyReport};++/// Whether local terminals answer to this process's identity: they run in+/// it, or in a server that kept the launcher's (a development build opting+/// out of taking its own).+fn terminals_share_this_identity() -> bool {+ crate::local_sessions::host_domain_name().is_none()+ || std::env::var_os("THINKTERM_NO_PRIVACY_DISCLAIM").is_some_and(|value| !value.is_empty())+}++/// Whether the permissions are the session server's, not this app's.+pub(crate) fn held_by_server() -> bool {+ !terminals_share_this_identity()+}++fn server_program() -> anyhow::Result<PathBuf> {+ Ok(std::env::current_exe()?.with_file_name("thinkterm-mux-server"))+}++/// What System Settings lists the permissions under, for the person to add+/// to a list by hand: this app's bundle, or the server binary inside it.+pub(crate) fn responsible_program() -> anyhow::Result<PathBuf> {+ if !terminals_share_this_identity() {+ return server_program();+ }+ let exe = std::env::current_exe()?;+ // `ThinkTerm.app/Contents/MacOS/thinkterm-gui` -> `ThinkTerm.app`.+ Ok(exe+ .ancestors()+ .find(|path| path.extension().is_some_and(|ext| ext == "app"))+ .map(PathBuf::from)+ .unwrap_or(exe))+}++const QUERY_TIMEOUT: Duration = Duration::from_secs(3);++struct PrivacyQuery {+ pending: Option<mpsc::Receiver<anyhow::Result<PrivacyReport>>>,+}++impl PrivacyQuery {+ fn query_with(+ &mut self,+ timeout: Duration,+ probe: impl FnOnce() -> anyhow::Result<PrivacyReport> + Send + 'static,+ ) -> anyhow::Result<PrivacyReport> {+ if self.pending.is_none() {+ let (tx, rx) = mpsc::channel();+ std::thread::Builder::new()+ .name("thinkterm-privacy-probe".into())+ .spawn(move || {+ let _ = tx.send(probe());+ })+ .context("starting the privacy probe")?;+ self.pending = Some(rx);+ }+ match self.pending.as_ref().unwrap().recv_timeout(timeout) {+ Ok(report) => {+ self.pending = None;+ report+ }+ Err(mpsc::RecvTimeoutError::Timeout) => {+ // macOS assessment can block spawn itself. Keep this one+ // worker until it answers; refocusing must not spawn more.+ anyhow::bail!("privacy check timed out after {timeout:?}")+ }+ Err(mpsc::RecvTimeoutError::Disconnected) => {+ self.pending = None;+ anyhow::bail!("privacy probe ended without a report")+ }+ }+ }+}++static QUERY: Mutex<PrivacyQuery> = Mutex::new(PrivacyQuery { pending: None });++/// Ask off the main thread. The deadline covers macOS assessment during+/// launch as well as the probe, and a stuck launch keeps only one worker.+pub(crate) fn query() -> anyhow::Result<PrivacyReport> {+ QUERY+ .try_lock()+ .map_err(|_| anyhow::anyhow!("privacy check is already running"))?+ .query_with(QUERY_TIMEOUT, query_report)+}++fn query_report() -> anyhow::Result<PrivacyReport> {+ if terminals_share_this_identity() {+ return Ok(privacy::probe());+ }+ let server = server_program()?;+ let mut command = Command::new(&server);+ command.arg(privacy::REPORT_OPTION);+ query_command(command, QUERY_TIMEOUT).with_context(|| format!("running {}", server.display()))+}++fn query_command(mut command: Command, timeout: Duration) -> anyhow::Result<PrivacyReport> {+ command+ .stdin(Stdio::null())+ .stdout(Stdio::piped())+ .stderr(Stdio::piped())+ .kill_on_drop(true);+ let deadline = Instant::now() + timeout;+ let output = smol::block_on(smol::future::or(+ async {+ command+ .output()+ .await+ .context("reading the privacy probe output")+ },+ async {+ smol::Timer::at(deadline).await;+ anyhow::bail!("privacy probe timed out after {timeout:?}")+ },+ ))?;+ anyhow::ensure!(+ output.status.success(),+ "privacy probe failed: {}",+ String::from_utf8_lossy(&output.stderr).trim()+ );+ serde_json::from_slice(output.stdout.trim_ascii())+ .context("reading the session server's privacy report")+}++/// One permission's page in System Settings › Privacy & Security.+pub(crate) fn settings_url(pane: &str) -> String {+ format!("x-apple.systempreferences:com.apple.preference.security?{pane}")+}++pub(crate) const FULL_DISK_ACCESS_PANE: &str = "Privacy_AllFiles";+pub(crate) const SCREEN_RECORDING_PANE: &str = "Privacy_ScreenCapture";+pub(crate) const MICROPHONE_PANE: &str = "Privacy_Microphone";+pub(crate) const CAMERA_PANE: &str = "Privacy_Camera";++#[cfg(test)]+mod tests {+ use super::*;+ use wezterm_mux_server_impl::privacy::PrivacyStatus;++ fn report() -> PrivacyReport {+ PrivacyReport {+ full_disk_access: PrivacyStatus::Granted,+ screen_recording: PrivacyStatus::NotGranted,+ microphone: PrivacyStatus::Unknown,+ camera: PrivacyStatus::Unknown,+ }+ }++ #[test]+ fn a_stalled_launch_times_out_without_starting_more_probes() {+ let mut query = PrivacyQuery { pending: None };+ let (release, wait) = mpsc::channel();+ let started = Instant::now();+ assert!(query+ .query_with(Duration::from_millis(20), move || {+ wait.recv().unwrap();+ Ok(report())+ })+ .is_err());+ assert!(query+ .query_with(Duration::from_millis(20), || {+ panic!("a second probe must not start while the first is pending")+ })+ .is_err());+ assert!(started.elapsed() < Duration::from_secs(1));+ release.send(()).unwrap();+ assert_eq!(+ query+ .query_with(Duration::from_secs(1), || unreachable!())+ .unwrap(),+ report()+ );+ assert!(query.pending.is_none());+ }++ #[test]+ fn the_probe_reads_a_report_and_a_failed_probe_can_be_retried() {+ let mut command = Command::new("/bin/sh");+ command.args([+ "-c",+ "printf '%s' '{\"full_disk_access\":\"granted\",\"screen_recording\":\"not_granted\"}'",+ ]);+ assert_eq!(+ query_command(command, Duration::from_secs(1)).unwrap(),+ report()+ );+ let mut failed = Command::new("/bin/sh");+ failed.args(["-c", "exit 1"]);+ assert!(query_command(failed, Duration::from_secs(1)).is_err());++ let mut query = PrivacyQuery { pending: None };+ assert!(query+ .query_with(Duration::from_secs(1), || { anyhow::bail!("probe failed") })+ .is_err());+ assert!(query.pending.is_none());+ assert_eq!(+ query+ .query_with(Duration::from_secs(1), || Ok(report()))+ .unwrap(),+ report()+ );+ }++ #[test]+ fn a_child_that_never_exits_is_cancelled_at_the_deadline() {+ let mut command = Command::new("/bin/sh");+ command.args(["-c", "exec sleep 30"]);+ let started = Instant::now();+ let error = query_command(command, Duration::from_millis(50)).unwrap_err();+ assert!(error.to_string().contains("timed out"));+ assert!(started.elapsed() < Duration::from_secs(2));+ }+}diff --git a/wezterm-gui/src/settings_window.rs b/wezterm-gui/src/settings_window.rsindex 2c74a989..a5e71908 100644--- a/wezterm-gui/src/settings_window.rs+++ b/wezterm-gui/src/settings_window.rs@@ -2,6 +2,8 @@ use crate::tab_icons::RgbExt as _;use crate::customglyph::{BlockKey, Poly};use crate::glyphcache::CachedGlyph;use crate::native_settings::AgentStatusPart;+use crate::native_settings::{NativeWorkspaceSettings, WorkMoment, WorkMoments};+use wezterm_mux_server_impl::privacy::PrivacyReport;use crate::quad::{HeapQuadAllocator, QuadTrait, TripleLayerQuadAllocator, TripleLayerQuadAllocatorTrait,};@@ -86,6 +88,10 @@ const HERO_MARK_SIZE: f32 = 108.0;const SWITCH_WIDTH: f32 = 76.0;const SWITCH_HEIGHT: f32 = 44.0;const SWITCH_KNOB_INSET: f32 = 4.0;+/// The ticked chips under a Notifications prompt, one per moment.+const WORK_MOMENT_CHIP_HEIGHT: f32 = 44.0;+const WORK_MOMENT_CHIP_GAP: f32 = 14.0;+const WORK_MOMENT_CHECK_SIDE: f32 = 24.0;// Matches termwindow::ui::tokens::SIDEBAR_ROW_HIGHLIGHT_RADIUS: the two// sidebars draw the same shape.const NAV_ROW_RADIUS: f32 = 20.0;@@ -912,6 +918,9 @@ enum SettingsSection {/// Sharing a terminal with other accounts on its machine, and later/// syncing with one's other devices.ShareSync,+ /// What macOS lets the programs run in terminals do, and where to allow+ /// it. A Mac's page only.+ Privacy,/// Not a page: what a search for it finds, which leads to the Tailscale/// group in Remote Hosts, where the tailnet is set up beside its/// machines.@@ -938,6 +947,7 @@ const BASE_SECTIONS: &[SettingsSection] = &[SettingsSection::Agents,SettingsSection::Web,SettingsSection::ShareSync,+ SettingsSection::Privacy,SettingsSection::Archived,SettingsSection::Keymap,SettingsSection::CommandPalette,@@ -1015,6 +1025,8 @@ fn initial_section() -> SettingsSection {"agents" => SettingsSection::Agents,"web" => SettingsSection::Web,"share" | "sharing" | "sharesync" | "share-sync" => SettingsSection::ShareSync,+ // A Mac's page only: elsewhere there is none to open.+ "privacy" | "permissions" if cfg!(target_os = "macos") => SettingsSection::Privacy,// The plugins are on the Sidebar page, the only place they show."plugins" => SettingsSection::Sidebar,"archived" => SettingsSection::Archived,@@ -1051,6 +1063,7 @@ impl SettingsSection {Self::Agents => crate::i18n::tr("settings-section-agents"),Self::Web => crate::i18n::tr("settings-section-web"),Self::ShareSync => crate::i18n::tr("settings-section-share-sync"),+ Self::Privacy => crate::i18n::tr("settings-section-privacy"),Self::Tailscale => crate::i18n::tr("settings-section-tailscale"),Self::Archived => crate::i18n::tr("settings-section-archived"),Self::Keymap => crate::i18n::tr("settings-section-keymap"),@@ -1076,6 +1089,7 @@ impl SettingsSection {Self::Agents => SettingsIcon::Agents,Self::Web => SettingsIcon::Web,Self::ShareSync => SettingsIcon::Share,+ Self::Privacy => SettingsIcon::Privacy,Self::Tailscale => SettingsIcon::Tailscale,Self::Archived => SettingsIcon::Archived,Self::Keymap => SettingsIcon::Keymap,@@ -1103,6 +1117,7 @@ impl SettingsSection {Self::Agents => TileColor::Orange,Self::Web => TileColor::Teal,Self::ShareSync => TileColor::Green,+ Self::Privacy => TileColor::Blue,Self::Tailscale => TileColor::Blue,Self::Archived => TileColor::Indigo,Self::Keymap => TileColor::Gray,@@ -1157,6 +1172,14 @@ impl SettingsSection {"Watch","Sync",],+ Self::Privacy => &[+ "Permissions",+ "Privacy",+ "Full Disk Access",+ "Screen Recording",+ "Microphone",+ "Camera",+ ],Self::Tailscale => &["Tailscale","Tailnet",@@ -1246,6 +1269,10 @@ impl SettingsSection {"Remote Files","SFTP","Idle Timeout",+ "Notifications",+ "Sounds",+ "Dock",+ "Badge",],Self::Agents => &["Agent",@@ -1396,6 +1423,16 @@ impl SettingsSection {&& ["settings-language", "settings-restore-pane-output"].iter().any(|key| crate::i18n::tr(key).to_lowercase().contains(query)))+ || (self == Self::Privacy+ && [+ "settings-privacy-heading",+ "settings-privacy-full-disk",+ "settings-privacy-screen",+ "settings-privacy-microphone",+ "settings-privacy-camera",+ ]+ .iter()+ .any(|key| crate::i18n::tr(key).to_lowercase().contains(query)))|| (self == Self::Appearance&& ["settings-window-opacity",@@ -1422,6 +1459,7 @@ impl SettingsSection {"settings-copy-on-select","settings-right-click","settings-right-click-paste",+ "settings-paste-confirmation","settings-copy-effect","settings-focus-follows-mouse","settings-split-animation",@@ -1484,6 +1522,16 @@ mod settings_search_tests {assert!(SettingsSection::Terminal.matches_search(&localized_label));}+ #[test]+ fn permissions_are_found_on_their_own_page() {+ for query in ["full disk access", "screen recording", "permissions", "camera"] {+ assert!(SettingsSection::Privacy.matches_search(query), "{}", query);+ assert!(!SettingsSection::General.matches_search(query), "{}", query);+ }+ let heading = crate::i18n::tr("settings-privacy-heading").to_lowercase();+ assert!(SettingsSection::Privacy.matches_search(&heading));+ }+#[test]fn tailscale_is_found_by_a_search_but_listed_nowhere() {// Its settings are in Remote Hosts; a search for them leads there.@@ -1999,6 +2047,79 @@ fn web_token_key(id: &str) -> u64 {hasher.finish()}+/// One way a thread's moments can prompt you, as the Notifications card+/// lists them, each with the moments it answers.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum WorkPrompt {+ Sound,+ SystemNotification,+ DockBadge,+}++impl WorkPrompt {+ fn label_key(self) -> &'static str {+ match self {+ Self::Sound => "settings-notification-sounds",+ Self::SystemNotification => "settings-system-notifications",+ Self::DockBadge => "settings-dock-badge",+ }+ }++ fn enabled(self, workspaces: &NativeWorkspaceSettings) -> bool {+ match self {+ Self::Sound => workspaces.notification_sounds_enabled,+ Self::SystemNotification => workspaces.system_notifications_enabled,+ Self::DockBadge => workspaces.dock_badge_enabled,+ }+ }++ fn moments(self, workspaces: &NativeWorkspaceSettings) -> WorkMoments {+ match self {+ Self::Sound => workspaces.notification_sound_moments,+ Self::SystemNotification => workspaces.system_notification_moments,+ Self::DockBadge => workspaces.dock_badge_moments,+ }+ }++ fn moments_mut(self, workspaces: &mut NativeWorkspaceSettings) -> &mut WorkMoments {+ match self {+ Self::Sound => &mut workspaces.notification_sound_moments,+ Self::SystemNotification => &mut workspaces.system_notification_moments,+ Self::DockBadge => &mut workspaces.dock_badge_moments,+ }+ }++ fn merge(self, from: &NativeWorkspaceSettings, into: &mut NativeWorkspaceSettings) {+ match self {+ Self::Sound => into.notification_sounds_enabled = from.notification_sounds_enabled,+ Self::SystemNotification => {+ into.system_notifications_enabled = from.system_notifications_enabled;+ }+ Self::DockBadge => into.dock_badge_enabled = from.dock_badge_enabled,+ }+ *self.moments_mut(into) = self.moments(from);+ }+}++/// What the programs in local terminals may do, as Settings › General last+/// found it (macOS).+#[derive(Debug, Clone)]+#[cfg_attr(not(target_os = "macos"), allow(dead_code))]+enum PrivacyCheck {+ /// Not looked yet, or due for another look.+ Stale,+ Checking,+ Done(Result<PrivacyReport, String>),+}++fn work_moment_label_key(moment: WorkMoment) -> &'static str {+ match moment {+ WorkMoment::Finished => "settings-work-moment-finished",+ WorkMoment::NeedsInput => "settings-work-moment-needs-input",+ WorkMoment::Error => "settings-work-moment-error",+ }+}+#[derive(Debug, Clone, Copy, PartialEq, Eq)]enum SettingsAction {SelectImportSource(ImportSource),@@ -2027,6 +2148,16 @@ enum SettingsAction {ToggleSharing,ToggleNotificationSounds,ToggleSystemNotifications,+ ToggleDockBadge,+ /// One moment's chip under a prompt in the Notifications card.+ ToggleWorkMoment(WorkPrompt, WorkMoment),+ /// A permission's page in System Settings › Privacy & Security.+ #[cfg(target_os = "macos")]+ OpenPrivacySettings(&'static str),+ /// Show the program the permissions belong to in Finder, to be dragged+ /// into a permission's list.+ #[cfg(target_os = "macos")]+ RevealPrivacyHolder,ToggleAgentStatusPart(AgentStatusPart),ToggleRemoteUpdateKeepsSessions,ToggleLocalSessionsViaMux,@@ -2135,6 +2266,7 @@ enum SettingsAction {SetScrollMode(crate::native_settings::NativeScrollMode),SetSelectionStyle(crate::native_settings::NativeSelectionStyle),ToggleCopyOnSelect,+ TogglePasteConfirmation,ToggleFocusFollowsMouse,SetRightClick(crate::native_settings::NativeRightClick),SetCopyEffect(crate::native_settings::NativeCopyEffect),@@ -2830,6 +2962,8 @@ struct SettingsUiState {tab_icon_glyph_input_dirty: bool,/// Two-step delete: the card whose Delete was clicked once.confirm_delete_tab_icon: Option<String>,+ /// The permissions card's last look (macOS).+ privacy: PrivacyCheck,}impl SettingsUiState {@@ -2910,6 +3044,7 @@ impl SettingsUiState {tab_icon_glyph_input: TextInputState::new(),tab_icon_glyph_input_dirty: false,confirm_delete_tab_icon: None,+ privacy: PrivacyCheck::Stale,}}}@@ -4212,6 +4347,15 @@ impl SettingsWindow {window.invalidate();Ok(true)}+ WindowEvent::FocusChanged(true) => {+ // Back from System Settings, perhaps having granted one: the+ // permissions card looks again when it is next painted.+ if matches!(self.ui.privacy, PrivacyCheck::Done(_)) {+ self.ui.privacy = PrivacyCheck::Stale;+ window.invalidate();+ }+ Ok(true)+ }WindowEvent::AppearanceChanged(appearance) => {self.appearance = appearance;self.refresh_chrome();@@ -6146,6 +6290,11 @@ impl SettingsWindow {sections.extend_from_slice(DEVELOPER_SECTIONS);}}+ // What macOS asks of programs run in terminals: other systems ask+ // nothing of the kind.+ if !cfg!(target_os = "macos") {+ sections.retain(|section| *section != SettingsSection::Privacy);+ }sections}@@ -6339,7 +6488,7 @@ impl SettingsWindow {self.ui.open_dropdown = None;self.native_settings.workspaces.notification_sounds_enabled =!self.native_settings.workspaces.notification_sounds_enabled;- match crate::native_settings::save(&self.native_settings) {+ match self.persist_work_prompt(WorkPrompt::Sound) {Ok(()) => {self.status = if self.native_settings.workspaces.notification_sounds_enabled{@@ -6361,7 +6510,7 @@ impl SettingsWindow {self.native_settings.workspaces.system_notifications_enabled =!self.native_settings.workspaces.system_notifications_enabled;let setting = crate::i18n::tr("settings-system-notifications");- self.status = match crate::native_settings::save(&self.native_settings) {+ self.status = match self.persist_work_prompt(WorkPrompt::SystemNotification) {Ok(()) => settings_tr("settings-status-saved", &[("setting", setting)]),Err(err) => settings_tr("settings-status-save-error",@@ -6369,6 +6518,32 @@ impl SettingsWindow {),};}+ SettingsAction::ToggleDockBadge => {+ self.ui.open_dropdown = None;+ self.native_settings.workspaces.dock_badge_enabled =+ !self.native_settings.workspaces.dock_badge_enabled;+ self.save_work_prompt(WorkPrompt::DockBadge);+ }+ SettingsAction::ToggleWorkMoment(prompt, moment) => {+ self.ui.open_dropdown = None;+ prompt+ .moments_mut(&mut self.native_settings.workspaces)+ .toggle(moment);+ self.save_work_prompt(prompt);+ }+ #[cfg(target_os = "macos")]+ SettingsAction::OpenPrivacySettings(pane) => {+ self.ui.open_dropdown = None;+ wezterm_open_url::open_url(&crate::privacy_status::settings_url(pane));+ }+ #[cfg(target_os = "macos")]+ SettingsAction::RevealPrivacyHolder => {+ self.ui.open_dropdown = None;+ match crate::privacy_status::responsible_program() {+ Ok(program) => wezterm_open_url::reveal_path(&program),+ Err(err) => log::warn!("finding the program permissions belong to: {err:#}"),+ }+ }SettingsAction::ToggleAgentStatusPart(part) => {self.ui.open_dropdown = None;part.toggle(&mut self.native_settings.chrome.agent_status_display);@@ -6768,6 +6943,19 @@ impl SettingsWindow {terminal.copy_on_select = on})}+ SettingsAction::TogglePasteConfirmation => {+ let on = !self.native_settings.terminal.paste_confirmation;+ let done = settings_tr(+ "settings-status-value-now",+ &[+ ("setting", crate::i18n::tr("settings-paste-confirmation")),+ ("value", crate::i18n::tr(if on { "common-on" } else { "common-off" })),+ ],+ );+ self.apply_terminal_change("settings-paste-confirmation", done, |terminal| {+ terminal.paste_confirmation = on+ })+ }SettingsAction::ToggleFocusFollowsMouse => {let on = !self.native_settings.terminal.focus_follows_mouse;let done = settings_tr(@@ -8518,6 +8706,7 @@ impl SettingsWindow {SettingsSection::Agents => self.paint_agents(layers, x, max_width)?,SettingsSection::Web => self.paint_web(layers, x, max_width)?,SettingsSection::ShareSync => self.paint_share_sync(layers, x, max_width)?,+ SettingsSection::Privacy => self.paint_privacy(layers, x, max_width)?,// Never selected: picking it opens Remote Hosts instead.SettingsSection::Tailscale => {}SettingsSection::Archived => self.paint_archived(layers, x, max_width)?,@@ -8960,6 +9149,7 @@ impl SettingsWindow {})?;}+let card_y = self.paint_card_heading(layers,x,@@ -11888,44 +12078,54 @@ impl SettingsWindow {)?;let bottom = self.paint_card(layers, x, card_y, max_width, |this, layers, top| {let mut rows = RowCursor::new(top, this);- let (tx, tw) = this.paint_row_tile(- layers,- row_x,- rows.y,- row_width,- SvgIcon::Bell,- TileColor::Red,- )?;- rows.add(this.paint_toggle_setting_row(- layers,- tx,- rows.y,- tw,- &crate::i18n::tr("settings-notification-sounds"),- &crate::i18n::tr("settings-notification-sounds-description"),- this.native_settings.workspaces.notification_sounds_enabled,- SettingsAction::ToggleNotificationSounds,- rows.rule(),- )?);- let (tx, tw) = this.paint_row_tile(- layers,- row_x,- rows.y,- row_width,- SvgIcon::BellRing,- TileColor::Red,- )?;- rows.add(this.paint_toggle_setting_row(- layers,- tx,- rows.y,- tw,- &crate::i18n::tr("settings-system-notifications"),- &crate::i18n::tr("settings-system-notifications-description"),- this.native_settings.workspaces.system_notifications_enabled,- SettingsAction::ToggleSystemNotifications,- rows.rule(),- )?);+ let mut prompts = vec![+ (+ WorkPrompt::Sound,+ SvgIcon::Bell,+ "settings-notification-sounds-description",+ SettingsAction::ToggleNotificationSounds,+ ),+ (+ WorkPrompt::SystemNotification,+ SvgIcon::BellRing,+ "settings-system-notifications-description",+ SettingsAction::ToggleSystemNotifications,+ ),+ ];+ // Only the Dock has a count to show on an application's icon.+ if cfg!(target_os = "macos") {+ prompts.push((+ WorkPrompt::DockBadge,+ SvgIcon::AppWindow,+ "settings-dock-badge-description",+ SettingsAction::ToggleDockBadge,+ ));+ }+ for (prompt, icon, description, action) in prompts {+ let enabled = prompt.enabled(&this.native_settings.workspaces);+ let moments = prompt.moments(&this.native_settings.workspaces);+ let (tx, tw) =+ this.paint_row_tile(layers, row_x, rows.y, row_width, icon, TileColor::Red)?;+ let extra = this.paint_toggle_setting_row(+ layers,+ tx,+ rows.y,+ tw,+ &crate::i18n::tr(prompt.label_key()),+ &crate::i18n::tr(description),+ enabled,+ action,+ rows.rule(),+ )?;+ // Under the description, whatever its length.+ let description_bottom = this.settings_row_description_y(rows.y)+ + this.metrics.cell_size.height as f32+ + extra;+ let chips_top = description_bottom + this.ui_px(WORK_MOMENT_CHIP_GAP);+ let chips_height =+ this.paint_work_moment_chips(layers, tx, chips_top, prompt, moments, enabled)?;+ rows.add(chips_top + chips_height - description_bottom + extra);+ }Ok(rows.bottom)})?;@@ -14062,6 +14262,26 @@ impl SettingsWindow {rows.rule(),)?);+ let (tx, tw) = this.paint_row_tile(+ layers,+ row_x,+ rows.y,+ row_width,+ SvgIcon::Shield,+ TileColor::Orange,+ )?;+ rows.add(this.paint_toggle_setting_row(+ layers,+ tx,+ rows.y,+ tw,+ &crate::i18n::tr("settings-paste-confirmation"),+ &crate::i18n::tr("settings-paste-confirmation-description"),+ this.native_settings.terminal.paste_confirmation,+ SettingsAction::TogglePasteConfirmation,+ rows.rule(),+ )?);+let options: Vec<(String, SettingsAction)> = NativeCopyEffect::ALL.iter().map(|effect| (localized_copy_effect_label(*effect), SettingsAction::SetCopyEffect(*effect)))@@ -17619,6 +17839,444 @@ impl SettingsWindow {Ok(extra)}+ /// The moments `prompt` answers, as a row of ticked chips starting at+ /// `x, y`: one per [`WorkMoment`], each flipped by a click. While the+ /// prompt is off they are greyed and keep what was chosen. Returns their+ /// height.+ #[allow(clippy::too_many_arguments)]+ fn paint_work_moment_chips(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ prompt: WorkPrompt,+ moments: WorkMoments,+ active: bool,+ ) -> anyhow::Result<f32> {+ let palette = self.palette();+ let font = Rc::clone(&self.ui_font);+ let height = self.ui_px(WORK_MOMENT_CHIP_HEIGHT);+ let check = self.ui_px(WORK_MOMENT_CHECK_SIDE);+ let pad = self.ui_px(12.0);+ let mut chip_x = x;+ for moment in WorkMoment::ALL {+ let label = crate::i18n::tr(work_moment_label_key(moment));+ let label_width = self.measure_text_width(&font, &label);+ let width = pad + check + self.ui_px(10.0) + label_width + pad + self.ui_px(4.0);+ let action = SettingsAction::ToggleWorkMoment(prompt, moment);+ let state = if !active {+ ControlState::Disabled+ } else if self.ui.interaction.pressed == Some(action) {+ ControlState::Pressed+ } else if self.ui.interaction.hovered == Some(action) {+ ControlState::Hovered+ } else {+ ControlState::Normal+ };+ if active {+ self.ui_context+ .push(rect(chip_x, y, width, height), WidgetKind::Button, action);+ }+ let (background, border) = state.colors(self.chrome_palette);+ self.draw_rounded_frame(+ layers,+ 0,+ chip_x,+ y,+ width,+ height,+ background,+ border,+ height / 2.0,+ )?;++ let check_x = chip_x + pad;+ let check_y = y + (height - check) / 2.0;+ let ticked = moments.includes(moment);+ if ticked {+ let fill = if active {+ self.chrome_palette.accent+ } else {+ palette.muted_text+ };+ self.draw_rounded_rect(+ layers,+ 0,+ check_x,+ check_y,+ check,+ check,+ fill,+ self.ui_px(6.0),+ )?;+ let glyph = (check * 0.75).round();+ self.draw_svg_icon(+ layers,+ SvgIcon::Check,+ check_x + (check - glyph) / 2.0,+ check_y + (check - glyph) / 2.0,+ glyph,+ palette.on_accent,+ )?;+ } else {+ self.draw_rounded_frame(+ layers,+ 0,+ check_x,+ check_y,+ check,+ check,+ palette.control_bg,+ palette.control_border,+ self.ui_px(6.0),+ )?;+ }+ let text_x = check_x + check + self.ui_px(10.0);+ self.draw_text(+ layers,+ &font,+ text_x,+ self.control_text_y(y, height),+ &label,+ if active {+ palette.text+ } else {+ palette.muted_text+ },+ label_width + self.ui_px(4.0),+ )?;+ chip_x += width + self.ui_px(10.0);+ }+ Ok(height)+ }++ fn persist_work_prompt(&mut self, prompt: WorkPrompt) -> anyhow::Result<()> {+ let workspaces = self.native_settings.workspaces.clone();+ let saved = crate::native_settings::update(|settings| {+ prompt.merge(&workspaces, &mut settings.workspaces);+ });+ self.set_native_settings(match &saved {+ Ok(settings) => settings.as_ref().clone(),+ Err(_) => crate::native_settings::load(),+ });+ saved.map(drop)+ }++ /// Save a change to one of the Notifications card's prompts, and show+ /// it on the Dock icon at once when that is the prompt that changed.+ fn save_work_prompt(&mut self, prompt: WorkPrompt) {+ let setting = crate::i18n::tr(prompt.label_key());+ self.status = match self.persist_work_prompt(prompt) {+ Ok(()) => settings_tr("settings-status-saved", &[("setting", setting)]),+ Err(err) => settings_tr(+ "settings-status-save-error",+ &[("setting", setting), ("error", format!("{err:#}"))],+ ),+ };+ if prompt == WorkPrompt::DockBadge {+ crate::workspace_threads::refresh_dock_badge();+ }+ }++ /// Look up what the programs in local terminals may do, off the main+ /// thread, and repaint once the answer is in.+ #[cfg(target_os = "macos")]+ fn start_privacy_check(&mut self) {+ self.ui.privacy = PrivacyCheck::Checking;+ let instance_id = self.instance_id;+ let spawned = std::thread::Builder::new()+ .name("thinkterm-privacy-check".into())+ .spawn(move || {+ let result = crate::privacy_status::query().map_err(|err| format!("{err:#}"));+ if let Err(err) = &result {+ log::warn!("privacy check: {err}");+ }+ promise::spawn::spawn_into_main_thread(async move {+ let Some(settings) = settings_window_for_instance(instance_id) else {+ return;+ };+ let mut settings = settings.borrow_mut();+ settings.ui.privacy = PrivacyCheck::Done(result);+ if let Some(window) = settings.window.as_ref() {+ window.invalidate();+ }+ })+ .detach();+ });+ if let Err(err) = spawned {+ self.ui.privacy = PrivacyCheck::Done(Err(format!("{err:#}")));+ }+ }++ /// Settings › Permissions: whose permissions they are -- every program+ /// run in a terminal is ThinkTerm to macOS -- and the card of them. A+ /// Mac's page only; listed nowhere else.+ fn paint_privacy(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ max_width: f32,+ ) -> anyhow::Result<()> {+ #[cfg(target_os = "macos")]+ {+ let palette = self.palette();+ let body_font = Rc::clone(&self.body_font);+ let scroll = self.ui.content_scroll.offset;+ let section_y = self.ui_px(CONTENT_SECTION_Y) - scroll;+ let lines = self.wrap_settings_text(+ &body_font,+ &crate::i18n::tr("settings-privacy-page-description"),+ max_width,+ );+ let last = self.draw_text_lines(+ layers,+ &body_font,+ x,+ section_y,+ &lines,+ palette.secondary_text,+ max_width,+ )?;+ let card_padding = self.ui_px(36.0);+ let bottom = self.paint_privacy_card(+ layers,+ x,+ section_y + last,+ max_width,+ x + card_padding,+ max_width - card_padding * 2.0,+ )?;+ self.ui.content_scroll.set_extents(+ self.content_viewport_extent(),+ self.settings_content_extent(bottom + scroll),+ );+ }+ #[cfg(not(target_os = "macos"))]+ let _ = (layers, x, max_width);+ Ok(())+ }++ /// Settings › Permissions' card on what macOS lets the programs in+ /// local terminals do: each permission as it stands with a way to its+ /// page in System Settings, then the program they belong to, to be added+ /// to a list by hand. Returns where the card ends.+ #[cfg(target_os = "macos")]+ #[allow(clippy::too_many_arguments)]+ fn paint_privacy_card(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ top: f32,+ max_width: f32,+ row_x: f32,+ row_width: f32,+ ) -> anyhow::Result<f32> {+ use crate::privacy_status::{+ CAMERA_PANE, FULL_DISK_ACCESS_PANE, MICROPHONE_PANE, SCREEN_RECORDING_PANE,+ };+ use wezterm_mux_server_impl::privacy::PrivacyStatus;+ if matches!(self.ui.privacy, PrivacyCheck::Stale) {+ self.start_privacy_check();+ }+ let card_y = self.paint_card_heading(+ layers,+ x,+ top,+ max_width,+ &crate::i18n::tr("settings-privacy-heading"),+ )?;+ let report = match &self.ui.privacy {+ PrivacyCheck::Done(Ok(report)) => Some(*report),+ _ => None,+ };+ let checking = matches!(+ self.ui.privacy,+ PrivacyCheck::Stale | PrivacyCheck::Checking+ );+ let held_by_server = crate::privacy_status::held_by_server();+ self.paint_card(layers, x, card_y, max_width, |this, layers, top| {+ let mut rows = RowCursor::new(top, this);+ let permissions = [+ (+ SvgIcon::FileText,+ TileColor::Gray,+ "settings-privacy-full-disk",+ "settings-privacy-full-disk-description",+ // Every program in every terminal past every folder at+ // once: what that risks, under what it is for.+ Some("settings-privacy-full-disk-caution"),+ FULL_DISK_ACCESS_PANE,+ report.map(|report| report.full_disk_access),+ ),+ (+ SvgIcon::Monitor,+ TileColor::Indigo,+ "settings-privacy-screen",+ "settings-privacy-screen-description",+ None,+ SCREEN_RECORDING_PANE,+ report.map(|report| report.screen_recording),+ ),+ (+ SvgIcon::Mic,+ TileColor::Orange,+ "settings-privacy-microphone",+ "settings-privacy-microphone-description",+ None,+ MICROPHONE_PANE,+ report.map(|report| report.microphone),+ ),+ (+ SvgIcon::Camera,+ TileColor::Teal,+ "settings-privacy-camera",+ "settings-privacy-camera-description",+ None,+ CAMERA_PANE,+ report.map(|report| report.camera),+ ),+ ];+ for (icon, color, label, description, caution, pane, status) in permissions {+ let (tx, tw) = this.paint_row_tile(layers, row_x, rows.y, row_width, icon, color)?;+ let (state, dot) = match status {+ _ if checking => ("settings-privacy-checking", this.palette().control_border),+ Some(PrivacyStatus::Granted) => {+ ("settings-privacy-granted", TileColor::Green.linear())+ }+ Some(PrivacyStatus::NotGranted) => {+ ("settings-privacy-not-granted", this.palette().muted_text)+ }+ Some(PrivacyStatus::Denied) => {+ ("settings-privacy-denied", TileColor::Red.linear())+ }+ Some(PrivacyStatus::NotAsked) => {+ ("settings-privacy-not-asked", this.palette().control_border)+ }+ Some(PrivacyStatus::Unknown) | None => {+ ("settings-privacy-unknown", this.palette().control_border)+ }+ };+ rows.add(this.paint_privacy_row(+ layers,+ tx,+ rows.y,+ tw,+ &crate::i18n::tr(label),+ &crate::i18n::tr(description),+ caution.map(crate::i18n::tr).as_deref(),+ &crate::i18n::tr(state),+ dot,+ SettingsAction::OpenPrivacySettings(pane),+ rows.rule(),+ )?);+ }+ let (tx, tw) = this.paint_row_tile(+ layers,+ row_x,+ rows.y,+ row_width,+ if held_by_server {+ SvgIcon::MuxServer+ } else {+ SvgIcon::AppWindow+ },+ TileColor::Slate,+ )?;+ rows.add(this.paint_action_setting_row(+ layers,+ tx,+ rows.y,+ tw,+ &crate::i18n::tr(if held_by_server {+ "settings-privacy-holder-server"+ } else {+ "settings-privacy-holder-app"+ }),+ &crate::i18n::tr("settings-privacy-holder-description"),+ &crate::i18n::tr("menu-reveal-finder"),+ SettingsAction::RevealPrivacyHolder,+ rows.rule(),+ )?);+ Ok(rows.bottom)+ })+ }++ /// A permission's row: its name and what it is for, then what allowing+ /// it risks where it has a `caution`; how it stands as a dot and a word,+ /// and a button to its page in System Settings.+ #[cfg(target_os = "macos")]+ #[allow(clippy::too_many_arguments)]+ fn paint_privacy_row(+ &mut self,+ layers: &mut TripleLayerQuadAllocator<'_>,+ x: f32,+ y: f32,+ width: f32,+ label: &str,+ description: &str,+ caution: Option<&str>,+ state: &str,+ dot_color: LinearRgba,+ action: SettingsAction,+ draw_top_rule: bool,+ ) -> anyhow::Result<f32> {+ let palette = self.palette();+ let ui_font = Rc::clone(&self.ui_font);+ if draw_top_rule {+ self.paint_separator(layers, x, y - self.ui_px(28.0), width)?;+ }+ let button = crate::i18n::tr("settings-privacy-open");+ let button_width = self.button_width_for_label(&button, 0.0);+ let button_x = x + width - button_width;+ let control_y = y + self.ui_px(4.0);+ let control_height = self.ui_px(CONTROL_HEIGHT);+ let dot = self.ui_px(14.0);+ let state_width = self.measure_text_width(&ui_font, state);+ let state_x = button_x - self.ui_px(20.0) - state_width;+ let dot_x = state_x - self.ui_px(10.0) - dot;+ let text_width = (dot_x - x - self.ui_px(24.0)).max(width * 0.35);++ self.draw_text(layers, &ui_font, x, y, label, palette.text, text_width)?;+ let mut extra = self.draw_row_description(layers, x, y, description, text_width)?;+ if let Some(caution) = caution {+ // Whole, and in a colour of its own: it is there to be read.+ let body_font = Rc::clone(&self.body_font);+ let step = self.description_line_step();+ let lines = self.wrap_settings_text(&body_font, caution, text_width);+ extra += step+ + self.draw_text_lines(+ layers,+ &body_font,+ x,+ self.settings_row_description_y(y) + extra + step,+ &lines,+ TileColor::Orange.linear(),+ text_width,+ )?;+ }+ self.draw_rounded_rect(+ layers,+ 0,+ dot_x,+ control_y + (control_height - dot) / 2.0,+ dot,+ dot,+ dot_color,+ dot / 2.0,+ )?;+ self.draw_text(+ layers,+ &ui_font,+ state_x,+ self.control_text_y(control_y, control_height),+ state,+ palette.secondary_text,+ state_width + self.ui_px(4.0),+ )?;+ self.draw_button(layers, button_x, control_y, button_width, &button, action)?;+ Ok(extra)+ }+/// A single-line band like `paint_toggle_setting_row_with_hint`, with a/// button on the right instead of a switch: the label and its hint/// icon on the left, the button centred in the band.diff --git a/wezterm-gui/src/termwindow/clipboard.rs b/wezterm-gui/src/termwindow/clipboard.rsindex 2b119bdc..f62874fe 100644--- a/wezterm-gui/src/termwindow/clipboard.rs+++ b/wezterm-gui/src/termwindow/clipboard.rs@@ -1,4 +1,4 @@-use crate::termwindow::TermWindowNotif;+use crate::termwindow::{ContextMenuApplicationAction, TermWindowNotif};use crate::TermWindow;use config::keyassignment::{ClipboardCopyDestination, ClipboardPasteSource};use mux::pane::{Pane, PaneId};@@ -103,11 +103,70 @@ impl TermWindow {mux.get_pane(pane_id)});if let Some(pane) = pane {- // Where the paste goes in, read before it does.- let cursor = pane.get_cursor_position();- if pane.send_paste(text).is_ok() {- self.light_up_terminal_paste(&pane, text, cursor);- }+ self.paste_text_into(&pane, text);+ }+ }++ /// Paste `text` into `pane`, the terminal or an overlay over it, asking+ /// first, when the setting is on, if its newlines would run what comes+ /// before them.+ pub(crate) fn paste_text_into(&mut self, pane: &Arc<dyn Pane>, text: &str) {+ if text.is_empty() {+ return;+ }+ // An overlay takes a paste in itself; only the program can run it.+ if crate::native_settings::paste_confirmation()+ && paste_needs_confirmation(text, pane.bracketed_paste())+ && self.pane_state(pane.pane_id()).overlay.is_none()+ {+ self.confirm_paste(pane.pane_id(), text.to_string());+ return;+ }+ self.deliver_paste(pane, text);+ }++ fn deliver_paste(&mut self, pane: &Arc<dyn Pane>, text: &str) {+ // Where the paste goes in, read before it does.+ let cursor = pane.get_cursor_position();+ if pane.send_paste(text).is_ok() {+ self.light_up_terminal_paste(pane, text, cursor);+ }+ }++ /// Ask, in a menu at the text cursor, before pasting `text` where its+ /// newlines would run what comes before them.+ fn confirm_paste(&mut self, pane_id: PaneId, text: String) {+ let Some(window) = self.window.clone() else {+ return;+ };+ let anchor = self+ .text_cursor_rect+ .map(|cell| window::Point::new(cell.min_x(), cell.max_y()))+ .or_else(|| self.current_mouse_event.as_ref().map(|event| event.coords))+ .unwrap_or_else(|| window::Point::new(0, 0));+ let header = window::ContextMenuItem::SectionHeader {+ label: crate::i18n::tr("paste-confirm-header"),+ };+ self.begin_context_menu_application_actions();+ let paste = self.context_menu_application_item_with_icon(+ crate::i18n::tr("paste-confirm-anyway"),+ window::ContextMenuIcon::Paste,+ ContextMenuApplicationAction::ResolvePaste(Some((pane_id, text))),+ true,+ );+ let cancel = self.context_menu_application_item_with_icon(+ crate::i18n::tr("paste-confirm-cancel"),+ window::ContextMenuIcon::Close,+ ContextMenuApplicationAction::ResolvePaste(None),+ true,+ );+ self.show_term_context_menu(&window, anchor, vec![header, paste, cancel]);+ }++ /// Paste what the person agreed to paste, should its pane still be there.+ pub(crate) fn paste_confirmed(&mut self, pane_id: PaneId, text: &str) {+ if let Some(pane) = Mux::get().get_pane(pane_id) {+ self.deliver_paste(&pane, text);}}@@ -126,3 +185,28 @@ impl TermWindow {}}}++/// Whether pasting `text` could run commands before the person sees them:+/// it breaks a line, and the program did not ask for pastes bracketed, so+/// each line goes in as if typed and entered. A bracketed paste cannot end+/// early -- the terminal strips the markers from it -- and a pane that+/// cannot tell is not asked about.+fn paste_needs_confirmation(text: &str, bracketed_paste: Option<bool>) -> bool {+ bracketed_paste == Some(false) && text.contains(['\n', '\r'])+}++#[cfg(test)]+mod tests {+ use super::paste_needs_confirmation;++ #[test]+ fn only_a_line_break_into_an_unbracketed_program_asks() {+ assert!(paste_needs_confirmation("ls\nrm -rf build\n", Some(false)));+ assert!(paste_needs_confirmation("make install\n", Some(false)));+ assert!(paste_needs_confirmation("a\rb", Some(false)));+ assert!(!paste_needs_confirmation("git status", Some(false)));+ assert!(!paste_needs_confirmation("ls\nrm -rf build\n", Some(true)));+ assert!(!paste_needs_confirmation("ls\n\x1b[201~rm -rf build\n", Some(true)));+ assert!(!paste_needs_confirmation("ls\nrm -rf build\n", None));+ }+}diff --git a/wezterm-gui/src/termwindow/link_open.rs b/wezterm-gui/src/termwindow/link_open.rsnew file mode 100644index 00000000..a5eda00a--- /dev/null+++ b/wezterm-gui/src/termwindow/link_open.rs@@ -0,0 +1,209 @@+//! Opening a link a terminal program printed. Any program can print one,+//! and OSC 8 lets it put any target behind any text, so a click only goes+//! straight through to a web page. A link that would hand itself to another+//! application asks first, and one carrying characters that do not show is+//! not opened at all: what the user saw is not what would open.++use crate::termwindow::ContextMenuApplicationAction;+use window::{ContextMenuIcon, ContextMenuItem};++/// How long a link may be in the menu that asks about it, in characters.+/// The rest is elided from the middle, keeping the scheme and the end.+const SHOWN_LINK_CHARS: usize = 72;++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum LinkOpen {+ /// A web page: the browser opens it, as it always has.+ Direct,+ /// Hands itself to another application: ask first.+ Confirm,+ /// Carries hidden characters, or could be an opener option.+ Refuse,+}++pub(crate) fn classify(uri: &str) -> LinkOpen {+ if wezterm_open_url::is_opener_option(uri) || uri.chars().any(is_hidden) {+ return LinkOpen::Refuse;+ }+ match uri.split_once(':') {+ Some((scheme, _))+ if scheme.eq_ignore_ascii_case("http") || scheme.eq_ignore_ascii_case("https") =>+ {+ LinkOpen::Direct+ }+ _ => LinkOpen::Confirm,+ }+}++/// Characters that take no room, steer the text's direction, or break the+/// line. A plain space shows, so it is left to the menu to display.+fn is_hidden(c: char) -> bool {+ c.is_control()+ || (c.is_whitespace() && c != ' ')+ || matches!(+ c,+ '\u{00AD}'+ | '\u{034F}'+ | '\u{061C}'+ | '\u{115F}'+ | '\u{1160}'+ | '\u{17B4}'+ | '\u{17B5}'+ | '\u{180B}'..='\u{180F}'+ | '\u{200B}'..='\u{200F}'+ | '\u{202A}'..='\u{202E}'+ | '\u{2060}'..='\u{206F}'+ | '\u{3164}'+ | '\u{FE00}'..='\u{FE0F}'+ | '\u{FEFF}'+ | '\u{FFA0}'+ | '\u{FFF9}'..='\u{FFFB}'+ | '\u{1D173}'..='\u{1D17A}'+ | '\u{E0000}'..='\u{E0FFF}'+ )+}++/// `uri` as the menu shows it: every hidden character spelled out as its+/// code point, and the middle elided past [`SHOWN_LINK_CHARS`].+fn shown_link(uri: &str) -> String {+ let mut shown = String::new();+ for c in uri.chars() {+ if is_hidden(c) {+ shown.push_str(&format!("<U+{:04X}>", c as u32));+ } else {+ shown.push(c);+ }+ }+ let count = shown.chars().count();+ if count <= SHOWN_LINK_CHARS {+ return shown;+ }+ let head = SHOWN_LINK_CHARS * 2 / 3;+ let tail = SHOWN_LINK_CHARS - head - 1;+ let mut elided: String = shown.chars().take(head).collect();+ elided.push('…');+ elided.extend(shown.chars().skip(count - tail));+ elided+}++impl crate::TermWindow {+ /// Open `uri`, a terminal link the user clicked that the `open-uri`+ /// event left to us: a web page at once, anything else after asking in+ /// a menu at `anchor`, and a link hiding characters not at all.+ pub(crate) fn open_terminal_link(&mut self, uri: String, anchor: ::window::Point) {+ let decision = classify(&uri);+ if decision == LinkOpen::Direct {+ wezterm_open_url::open_url(&uri);+ return;+ }+ let Some(window) = self.window.as_ref().cloned() else {+ return;+ };+ let header = ContextMenuItem::SectionHeader {+ label: shown_link(&uri),+ };+ self.begin_context_menu_application_actions();+ let items = if decision == LinkOpen::Refuse {+ log::warn!("not opening an unsafe terminal link");+ let refused = self.context_menu_application_item_with_icon(+ crate::i18n::tr("link-refused-unsafe"),+ ContextMenuIcon::Warning,+ ContextMenuApplicationAction::ResolveTerminalLink(None),+ false,+ );+ vec![header, refused]+ } else {+ let open = self.context_menu_application_item_with_icon(+ crate::i18n::tr("link-open-other-app"),+ ContextMenuIcon::ExternalLink,+ ContextMenuApplicationAction::ResolveTerminalLink(Some(uri)),+ true,+ );+ let cancel = self.context_menu_application_item_with_icon(+ crate::i18n::tr("link-open-cancel"),+ ContextMenuIcon::Close,+ ContextMenuApplicationAction::ResolveTerminalLink(None),+ true,+ );+ vec![header, open, cancel]+ };+ self.show_term_context_menu(&window, anchor, items);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn web_pages_open_directly() {+ assert_eq!(classify("https://example.com/a?b=c"), LinkOpen::Direct);+ assert_eq!(classify("http://192.0.2.1:8080/"), LinkOpen::Direct);+ assert_eq!(classify("HTTPS://example.com"), LinkOpen::Direct);+ }++ #[test]+ fn opener_options_are_refused_before_confirmation() {+ for target in [+ "-a/home/user/Downloads/example.app",+ "--args",+ "--help",+ "-",+ ] {+ assert_eq!(classify(target), LinkOpen::Refuse, "{}", target);+ }+ assert_eq!(classify("./-notes.txt"), LinkOpen::Confirm);+ assert_eq!(classify("file:///home/user/-notes.txt"), LinkOpen::Confirm);+ assert_eq!(classify("https://example.com/-a"), LinkOpen::Direct);+ }++ #[test]+ fn other_schemes_ask_first() {+ for uri in [+ "file:///Applications/Example.app",+ "file:///home/user/notes.txt",+ "mailto:[email protected]",+ "vscode://file/home/user/main.rs:10",+ "ssh://devbox",+ "x-example-app:run",+ "httpx://example.com",+ "no scheme at all",+ ] {+ assert_eq!(classify(uri), LinkOpen::Confirm, "{uri}");+ }+ }++ #[test]+ fn hidden_characters_are_refused_whatever_the_scheme() {+ for uri in [+ "https://exa\u{200B}mple.com",+ "https://example.com/\u{202E}gpj.exe",+ "https://example.com\n/path",+ "file:///home/user/a\u{2028}b",+ "https://example.com/\u{00A0}",+ "https://example.com/\u{FEFF}",+ "https://example.com/\u{1b}[31m",+ "https://example.com/\u{E0041}",+ ] {+ assert_eq!(classify(uri), LinkOpen::Refuse, "{uri:?}");+ }+ assert_eq!(+ classify("file:///home/user/my notes.txt"),+ LinkOpen::Confirm+ );+ }++ #[test]+ fn the_menu_spells_out_hidden_characters_and_elides_the_middle() {+ assert_eq!(+ shown_link("https://exa\u{200B}mple.com"),+ "https://exa<U+200B>mple.com"+ );+ let long = format!("file:///home/user/{}/main.rs", "deep/".repeat(40));+ let shown = shown_link(&long);+ assert_eq!(shown.chars().count(), SHOWN_LINK_CHARS);+ assert!(shown.starts_with("file:///home/user/deep/"));+ assert!(shown.ends_with("/main.rs"));+ assert!(shown.contains('…'));+ }+}diff --git a/wezterm-gui/src/termwindow/mod.rs b/wezterm-gui/src/termwindow/mod.rsindex 574e5c8b..3c44114b 100644--- a/wezterm-gui/src/termwindow/mod.rs+++ b/wezterm-gui/src/termwindow/mod.rs@@ -151,6 +151,7 @@ pub mod charselect;pub mod clipboard;pub mod content_view;pub mod keyevent;+mod link_open;pub(crate) mod live_overview;pub mod modal;mod mouseevent;@@ -742,6 +743,12 @@ pub(crate) enum ContextMenuApplicationAction {CopyRemotePreviewAll,/// Answer to "these files already exist" for a queued local copy.ResolveLocalCopyConflict(transfer_walk::ConflictChoice),+ /// Answer to "open this terminal link in another app?": the link to+ /// open, or `None` to leave it.+ ResolveTerminalLink(Option<String>),+ /// Answer to "this paste could run commands, paste anyway?": the pane+ /// and the text to paste into it, or `None` to leave it.+ ResolvePaste(Option<(PaneId, String)>),}/// The scrollbar track a thumb, or the space above or below it, belongs@@ -2934,6 +2941,9 @@ pub struct TermWindow {last_mouse_coords: (usize, i64),window_drag_position: Option<MouseEvent>,current_mouse_event: Option<MouseEvent>,+ /// The active pane's cursor cell as last painted, in window pixels:+ /// where a question about a paste is asked.+ text_cursor_rect: Option<Rect>,prev_cursor: PrevCursorPos,last_scroll_info: RenderableDimensions,@@ -4988,6 +4998,7 @@ impl TermWindow {last_mouse_coords: (0, -1),window_drag_position: None,current_mouse_event: None,+ text_cursor_rect: None,current_modifier_and_leds: Default::default(),prev_cursor: PrevCursorPos::new(),last_scroll_info: RenderableDimensions::default(),@@ -5852,9 +5863,8 @@ impl TermWindow {Some(pane) => pane,None => return Ok(true),};- let cursor = pane.get_cursor_position();- pane.send_paste(text.as_str())?;- self.light_up_terminal_paste(&pane, &text, cursor);+ // Dropped text is a paste, and asks first like one.+ self.paste_text_into(&pane, &text);Ok(true)}WindowEvent::DroppedUrl(urls) => {@@ -6378,6 +6388,9 @@ impl TermWindow {}}crate::workspace_threads::refresh_thread_work_for_pane(pane_id);+ // Blocked and Error share NeedsAttention, but the Dock+ // can count just one of them.+ crate::workspace_threads::schedule_dock_badge_refresh();// Waiting -> error leaves the aggregate NeedsAttention// unchanged, but changes its icon. Decide from what this// window displays, not from the aggregate's changed bit.@@ -9797,6 +9810,7 @@ impl TermWindow {cell_size,);win.set_text_cursor_position(r);+ self.text_cursor_rect = Some(r);}fn activate_window(&mut self, window_idx: usize) -> anyhow::Result<()> {@@ -12022,13 +12036,21 @@ impl TermWindow {if let Some(link) = self.current_highlight.as_ref().cloned() {let window = GuiWin::new(self);let pane = MuxPane(pane.pane_id());+ // Where a link that asks first puts its menu.+ let anchor = self+ .current_mouse_event+ .as_ref()+ .map(|event| event.coords)+ .unwrap_or_else(|| ::window::Point::new(0, 0));async fn open_uri(lua: Option<Rc<mlua::Lua>>,window: GuiWin,pane: MuxPane,link: String,+ anchor: ::window::Point,) -> anyhow::Result<()> {+ let term_window = window.window.clone();let default_click = match lua {Some(lua) => {let args = lua.pack_multi((window, pane, link.clone()))?;@@ -12042,14 +12064,20 @@ impl TermWindow {None => true,};if default_click {- log::info!("clicking {}", link);- wezterm_open_url::open_url(&link);+ if link_open::classify(&link) == link_open::LinkOpen::Direct {+ log::info!("clicking {}", link);+ wezterm_open_url::open_url(&link);+ } else {+ term_window.notify(TermWindowNotif::Apply(Box::new(move |myself| {+ myself.open_terminal_link(link, anchor);+ })));+ }}Ok(())}promise::spawn::spawn(config::with_lua_config_on_main_thread(move |lua| {- open_uri(lua, window, pane, link.uri().to_string())+ open_uri(lua, window, pane, link.uri().to_string(), anchor)})).detach();}diff --git a/wezterm-gui/src/termwindow/ui/context_menu.rs b/wezterm-gui/src/termwindow/ui/context_menu.rsindex 73234333..23699abd 100644--- a/wezterm-gui/src/termwindow/ui/context_menu.rs+++ b/wezterm-gui/src/termwindow/ui/context_menu.rs@@ -502,6 +502,17 @@ impl crate::TermWindow {crate::termwindow::ContextMenuApplicationAction::ResolveRemoteConfirm(proceed) => {self.resolve_pending_remote_confirm(proceed);}+ crate::termwindow::ContextMenuApplicationAction::ResolveTerminalLink(link) => {+ if let Some(link) = link {+ log::info!("clicking {}", link);+ wezterm_open_url::open_url(&link);+ }+ }+ crate::termwindow::ContextMenuApplicationAction::ResolvePaste(paste) => {+ if let Some((pane_id, text)) = paste {+ self.paste_confirmed(pane_id, &text);+ }+ }crate::termwindow::ContextMenuApplicationAction::CopyRemotePreviewSelection => {self.copy_right_sidebar_selected_file_preview_text();}diff --git a/wezterm-gui/src/termwindow/ui/icons.rs b/wezterm-gui/src/termwindow/ui/icons.rsindex f4ebcb7d..cc83f682 100644--- a/wezterm-gui/src/termwindow/ui/icons.rs+++ b/wezterm-gui/src/termwindow/ui/icons.rs@@ -131,6 +131,8 @@ pub enum SvgIcon {KeyRound,LogOut,Monitor,+ Mic,+ Camera,Network,/// The mux server of the README's architecture diagram: a host whose/// sessions live on it, which is what ThinkTerm Connect means.@@ -428,6 +430,8 @@ impl SvgIcon {Self::KeyRound => include_bytes!("../../../../third_party/lucide/icons/key-round.svg"),Self::LogOut => include_bytes!("../../../../third_party/lucide/icons/log-out.svg"),Self::Monitor => include_bytes!("../../../../third_party/lucide/icons/monitor.svg"),+ Self::Mic => include_bytes!("../../../../third_party/lucide/icons/mic.svg"),+ Self::Camera => include_bytes!("../../../../third_party/lucide/icons/camera.svg"),Self::Apple => include_bytes!("../../../../third_party/simple-icons/icons/apple.svg"),Self::Network => include_bytes!("../../../../third_party/lucide/icons/network.svg"),Self::MuxServer => include_bytes!("../../../../assets/ui/mux-server.svg"),@@ -957,6 +961,9 @@ mod tests {SvgIcon::Apple,SvgIcon::Monitor,SvgIcon::Network,+ // Settings › General's permissions.+ SvgIcon::Mic,+ SvgIcon::Camera,// What a plugin's panel is shown by in the selector.SvgIcon::Activity,SvgIcon::Bug,diff --git a/wezterm-gui/src/ui/icons.rs b/wezterm-gui/src/ui/icons.rsindex b34a361a..cdb2d98a 100644--- a/wezterm-gui/src/ui/icons.rs+++ b/wezterm-gui/src/ui/icons.rs@@ -20,6 +20,7 @@ pub(crate) enum SettingsIcon {Backup,Web,Share,+ Privacy,Tailscale,CommandPalette,Search,@@ -48,6 +49,7 @@ impl SettingsIcon {Self::Backup => SvgIcon::Save,Self::Web => SvgIcon::Globe,Self::Share => SvgIcon::Share,+ Self::Privacy => SvgIcon::Shield,Self::Tailscale => SvgIcon::Network,Self::CommandPalette => SvgIcon::SquareTerminal,Self::Search => SvgIcon::Search,diff --git a/wezterm-gui/src/workspace_threads.rs b/wezterm-gui/src/workspace_threads.rsindex 80de6a81..41ad49d5 100644--- a/wezterm-gui/src/workspace_threads.rs+++ b/wezterm-gui/src/workspace_threads.rs@@ -1,4 +1,5 @@use anyhow::{ensure, Context, Result};+use crate::native_settings::{WorkMoment, WorkMoments};use chrono::Utc;use config::keyassignment::{SpawnCommand, SpawnTabDomain};use fluent_bundle::FluentArgs;@@ -206,15 +207,15 @@ pub struct WorkspaceThread {pub work_needs_attention: bool,/// The user acknowledged the *current* waiting episode (any keypress in/// the active workspace does). The badge may relight silently while the- /// agent is still waiting, but the needs-input sound must not replay+ /// agent is still waiting, but the same attention kind must not replay/// until the state genuinely leaves and re-enters attention.#[serde(skip)]pub work_attention_acknowledged: bool,- /// Panes whose waiting has already rung this episode. A pane newly- /// joining the waiting set is a new question and rings even while- /// others are still waiting; a pane merely re-observed stays quiet.+ /// Each waiting pane's last attention kind. A new pane or a changed+ /// kind may ring; re-observing the same wait stays quiet even after+ /// a keypress acknowledges it. Replaced on each scan, cleared on exit.#[serde(skip)]- pub work_waiting_panes: std::collections::HashSet<PaneId>,+ pub work_waiting_panes: HashMap<PaneId, WorkMoment>,#[serde(default)]pub work_finished_unseen: bool,}@@ -515,7 +516,7 @@ pub struct ThreadWorkNotification {pub status: WorkspaceThreadWorkStatus,}-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, PartialEq, Eq)]struct WorkspaceThreadWorkChange {changed: bool,should_persist: bool,@@ -523,6 +524,8 @@ struct WorkspaceThreadWorkChange {/// the observation that first crosses into the state, so re-scanning a/// thread that has not moved stays quiet without any extra bookkeeping.announce: Option<WorkAnnouncement>,+ /// Panes newly waiting or reporting a different attention kind.+ new_waiting_panes: Vec<(PaneId, WorkMoment)>,}/// A transition is at most one of these, so a single field makes it impossible@@ -790,6 +793,7 @@ static STORE_IS_UNREADABLE: AtomicBool = AtomicBool::new(false);static NEXT_SPACE_OWNER_ID: AtomicU64 = AtomicU64::new(1);fn publish_thinkterm_session_changed() {wezterm_mux_server_impl::thinkterm_session::publish_changed();+ schedule_dock_badge_refresh();}pub fn workspace_thread_store_path() -> PathBuf {@@ -3056,11 +3060,119 @@ fn should_play_work_sound(}}-fn announce_work(announcement: WorkAnnouncement, finished_after: Option<Duration>) {+fn no_work_moments() -> WorkMoments {+ WorkMoments {+ finished: false,+ needs_input: false,+ error: false,+ }+}++fn attention_moment(+ agent: Option<WorkspaceThreadWorkStatus>,+ agent_errored: bool,+ progress: &Progress,+) -> Option<WorkMoment> {+ match agent {+ Some(WorkspaceThreadWorkStatus::NeedsAttention) => Some(if agent_errored {+ WorkMoment::Error+ } else {+ WorkMoment::NeedsInput+ }),+ Some(_) => None,+ None if reports_native_error(agent, progress) => Some(WorkMoment::Error),+ None => None,+ }+}++fn pane_attention_moment(pane: &dyn Pane) -> Option<WorkMoment> {+ let agent = crate::agent_status::enabled()+ .then(|| crate::agent_status::agent_work_status(pane))+ .flatten();+ let errored = pane+ .agent_status()+ .is_some_and(|status| status.state == crate::agent_status::AgentState::Error);+ attention_moment(agent, errored, &pane.get_progress())+}++fn collect_work_moments(moments: impl IntoIterator<Item = WorkMoment>) -> WorkMoments {+ let mut collected = no_work_moments();+ for moment in moments {+ match moment {+ WorkMoment::Finished => collected.finished = true,+ WorkMoment::NeedsInput => collected.needs_input = true,+ WorkMoment::Error => collected.error = true,+ }+ }+ collected+}++fn first_work_moment(+ moments: WorkMoments,+ enabled: impl Fn(WorkMoment) -> bool,+) -> Option<WorkMoment> {+ WorkMoment::ALL+ .iter()+ .copied()+ .find(|moment| moments.includes(*moment) && enabled(*moment))+}++/// A thread can have both a failed build and an agent waiting for input.+/// Keep both kinds so a prompt's filter never masks the other one.+fn workspace_attention_moments(workspace: &str) -> WorkMoments {+ let mux = Mux::get();+ let moments = mux+ .iter_windows_in_workspace(workspace)+ .into_iter()+ .flat_map(|window_id| {+ let Some(window) = mux.get_window(window_id) else {+ return Vec::new();+ };+ let tabs = (0..window.len())+ .filter_map(|idx| window.get_by_idx(idx).cloned())+ .collect::<Vec<_>>();+ drop(window);+ tabs.iter()+ .flat_map(|tab| {+ tab.iter_all_panes()+ .into_iter()+ .filter_map(|pane| pane_attention_moment(pane.as_ref()))+ })+ .collect::<Vec<_>>()+ });+ collect_work_moments(moments)+}++/// Whether a pane's own progress report says it stopped on an error. It+/// counts only where it set the pane's status -- an agent the pane runs+/// speaks for it instead, as in `scan_workspace_work_status`.+fn reports_native_error(agent: Option<WorkspaceThreadWorkStatus>, progress: &Progress) -> bool {+ agent.is_none() && matches!(progress, Progress::Error(_))+}++/// Only this transition's new attention kinds contribute: an old error in+/// another pane must not turn an input request into an error prompt.+fn work_moments(+ announcement: WorkAnnouncement,+ new_waiting_panes: &[(PaneId, WorkMoment)],+) -> WorkMoments {+ match announcement {+ WorkAnnouncement::Finished => collect_work_moments([WorkMoment::Finished]),+ WorkAnnouncement::NeedsInput => {+ collect_work_moments(new_waiting_panes.iter().map(|(_, moment)| *moment))+ }+ }+}++fn announce_work(+ moment: WorkMoment,+ announcement: WorkAnnouncement,+ finished_after: Option<Duration>,+) {if std::env::var_os(DISABLE_SOUND_ENV).is_some() {return;}- if !crate::native_settings::notification_sounds_enabled() {+ if !crate::native_settings::notification_sound_for(moment) {return;}if !should_play_work_sound(announcement, finished_after) {@@ -3104,11 +3216,16 @@ fn can_notify_system() -> bool {/// its program stopped on an error -- when nobody is looking at ThinkTerm./// The same moments the sounds mark, with the program's own words when it/// gave any.-fn notify_system(workspace: &str, announcement: WorkAnnouncement, finished_after: Option<Duration>) {+fn notify_system(+ workspace: &str,+ moment: WorkMoment,+ announcement: WorkAnnouncement,+ finished_after: Option<Duration>,+) {if std::env::var_os(DISABLE_SOUND_ENV).is_some()|| crate::frontend::try_front_end().is_none()|| !can_notify_system()- || !crate::native_settings::system_notifications_enabled()+ || !crate::native_settings::system_notification_for(moment)|| crate::termwindow::app_has_focus()|| !should_play_work_sound(announcement, finished_after){@@ -3126,13 +3243,10 @@ fn notify_system(workspace: &str, announcement: WorkAnnouncement, finished_afternotified.retain(|_, at| now.duration_since(*at) < SYSTEM_NOTIFICATION_INTERVAL);notified.insert(workspace.to_string(), now);}- let errored = crate::agent_status::any_agent_in_workspace(workspace, |agent| {- agent.state == crate::agent_status::AgentState::Error- });- let state = crate::i18n::tr(match announcement {- WorkAnnouncement::Finished => "notification-thread-finished",- WorkAnnouncement::NeedsInput if errored => "notification-thread-error",- WorkAnnouncement::NeedsInput => "notification-thread-needs-input",+ let state = crate::i18n::tr(match moment {+ WorkMoment::Finished => "notification-thread-finished",+ WorkMoment::Error => "notification-thread-error",+ WorkMoment::NeedsInput => "notification-thread-needs-input",});let thread = thread_display_name_for_workspace(workspace).unwrap_or_else(|| workspace.to_string());let reason = crate::agent_status::workspace_reason(workspace).unwrap_or_default();@@ -3146,6 +3260,98 @@ fn notify_system(workspace: &str, announcement: WorkAnnouncement, finished_after);}+/// The moments an unseen thread's status stands for, if it is unseen work.+fn unseen_work_moments(status: WorkspaceThreadWorkStatus, attention: WorkMoments) -> WorkMoments {+ match status {+ WorkspaceThreadWorkStatus::FinishedUnseen => collect_work_moments([WorkMoment::Finished]),+ WorkspaceThreadWorkStatus::NeedsAttention => attention,+ WorkspaceThreadWorkStatus::Running | WorkspaceThreadWorkStatus::Idle => no_work_moments(),+ }+}++/// How many threads the Dock icon counts: the ones the notification bell+/// lists, narrowed to `moments`.+fn dock_badge_count(moments: WorkMoments) -> usize {+ // Collected first: asking about agents must not happen under the store.+ let unseen: Vec<(String, WorkspaceThreadWorkStatus)> = {+ let store = THREAD_STORE.lock();+ store+ .projects+ .iter()+ .flat_map(|project| {+ project.threads.iter().filter_map(move |thread| {+ let status = thread.work_status();+ if !matches!(+ status,+ WorkspaceThreadWorkStatus::NeedsAttention+ | WorkspaceThreadWorkStatus::FinishedUnseen+ ) {+ return None;+ }+ let workspace = thread+ .materialized_workspace_name+ .clone()+ .unwrap_or_else(|| workspace_name_for_thread(&project.id, &thread.id));+ Some((workspace, status))+ })+ })+ .collect()+ };+ unseen+ .into_iter()+ .filter(|(workspace, status)| {+ let attention = if *status == WorkspaceThreadWorkStatus::NeedsAttention {+ workspace_attention_moments(workspace)+ } else {+ no_work_moments()+ };+ first_work_moment(unseen_work_moments(*status, attention), |moment| {+ moments.includes(moment)+ })+ .is_some()+ })+ .count()+}++static DOCK_BADGE_REFRESH_PENDING: AtomicBool = AtomicBool::new(false);++lazy_static::lazy_static! {+ /// What the Dock icon shows now, so an unchanged count is not set again.+ static ref DOCK_BADGE_SHOWN: Mutex<Option<String>> = Mutex::new(None);+}++/// Bring the Dock icon's count up to date soon, on the main thread: what+/// changed the threads may still hold the store, or run elsewhere.+pub(crate) fn schedule_dock_badge_refresh() {+ if !cfg!(target_os = "macos") || !promise::spawn::is_scheduler_configured() {+ return;+ }+ if DOCK_BADGE_REFRESH_PENDING.swap(true, Ordering::AcqRel) {+ return;+ }+ promise::spawn::spawn_into_main_thread(async {+ DOCK_BADGE_REFRESH_PENDING.store(false, Ordering::Release);+ refresh_dock_badge();+ })+ .detach();+}++/// Show on the Dock icon how many threads have unseen work of the moments+/// chosen for it; nothing when there is none or it is turned off.+pub fn refresh_dock_badge() {+ let count = crate::native_settings::dock_badge_moments().map_or(0, dock_badge_count);+ let label = (count > 0).then(|| count.to_string());+ let mut shown = DOCK_BADGE_SHOWN.lock();+ if *shown == label {+ return;+ }+ use ::window::ConnectionOps;+ if let Some(connection) = ::window::Connection::get() {+ connection.set_dock_badge(label.as_deref());+ *shown = label;+ }+}+pub fn refresh_thread_work_for_workspace(workspace: &str) -> bool {let (raw_observed, waiting_panes) = scan_workspace_work_status(workspace);let observed = debounce_work_status(workspace, raw_observed);@@ -3168,8 +3374,17 @@ pub fn refresh_thread_work_for_workspace(workspace: &str) -> bool {}};if let Some(announcement) = change.announce {- announce_work(announcement, finished_after);- notify_system(workspace, announcement, finished_after);+ let moments = work_moments(announcement, &change.new_waiting_panes);+ if let Some(moment) =+ first_work_moment(moments, crate::native_settings::notification_sound_for)+ {+ announce_work(moment, announcement, finished_after);+ }+ if let Some(moment) =+ first_work_moment(moments, crate::native_settings::system_notification_for)+ {+ notify_system(workspace, moment, announcement, finished_after);+ }}if change.should_persist {schedule_workspace_thread_store_persist();@@ -3189,9 +3404,15 @@ pub fn refresh_all_thread_work() -> bool {for workspace in workspaces {changed |= refresh_thread_work_for_workspace(&workspace);}+ // Unseen work saved by the last run counts before anything changes.+ if !DOCK_BADGE_PRIMED.swap(true, Ordering::AcqRel) {+ schedule_dock_badge_refresh();+ }changed}+static DOCK_BADGE_PRIMED: AtomicBool = AtomicBool::new(false);+pub fn acknowledge_thread_work_for_workspace(workspace: &str) -> bool {WORK_SOUND_TIMING.lock().forget(workspace);let mut store = THREAD_STORE.lock();@@ -7743,7 +7964,7 @@ impl WorkspaceThreadStore {work_is_running: bool,work_needs_attention: bool,work_attention_acknowledged: bool,- work_waiting_panes: std::collections::HashSet<PaneId>,+ work_waiting_panes: HashMap<PaneId, WorkMoment>,work_finished_unseen: bool,}@@ -8198,7 +8419,7 @@ impl WorkspaceThreadStore {&mut self,workspace: &str,observed: WorkspaceThreadWorkStatus,- waiting_panes: &[PaneId],+ waiting_panes: &[(PaneId, WorkMoment)],) -> Option<WorkspaceThreadWorkChange> {for project in &mut self.projects {let project_id = project.id.clone();@@ -8244,6 +8465,7 @@ impl WorkspaceThreadStore {changed,should_persist,announce: None,+ new_waiting_panes: Vec::new(),};}}@@ -8252,6 +8474,7 @@ impl WorkspaceThreadStore {changed: false,should_persist: false,announce: None,+ new_waiting_panes: Vec::new(),}}@@ -8270,6 +8493,7 @@ impl WorkspaceThreadStore {changed,should_persist,announce: None,+ new_waiting_panes: Vec::new(),};}}@@ -8278,6 +8502,7 @@ impl WorkspaceThreadStore {changed: false,should_persist: false,announce: None,+ new_waiting_panes: Vec::new(),}}@@ -8889,7 +9114,7 @@ impl WorkspaceThread {fn observe_work_status(&mut self,observed: WorkspaceThreadWorkStatus,- waiting_panes: &[PaneId],+ waiting_panes: &[(PaneId, WorkMoment)],) -> WorkspaceThreadWorkChange {match observed {WorkspaceThreadWorkStatus::Running => {@@ -8907,26 +9132,27 @@ impl WorkspaceThread {changed,should_persist,announce: None,+ new_waiting_panes: Vec::new(),}}WorkspaceThreadWorkStatus::NeedsAttention => {let changed = !self.work_needs_attention;self.work_needs_attention = true;- // One ring per pane per waiting episode: a pane newly- // joining the waiting set is a new question and rings even- // while other agents are still waiting; a pane merely- // re-observed stays quiet. That last part is load-bearing —- // typing an answer into the agent's own question form- // acknowledges and re-observes the same pane every scan,- // and ringing there would ring on every keystroke.- let new_waiter = waiting_panes+ // A new waiter or a change from input to error may ring.+ // Re-observing the same kind stays quiet: typing into an+ // agent's question acknowledges and re-observes the pane+ // on every keypress without starting a new wait.+ let new_waiting_panes: Vec<_> = waiting_panes.iter()- .any(|pane| !self.work_waiting_panes.contains(pane));+ .copied()+ .filter(|(pane, moment)| self.work_waiting_panes.get(pane) != Some(moment))+ .collect();self.work_waiting_panes = waiting_panes.iter().copied().collect();WorkspaceThreadWorkChange {changed,should_persist: false,- announce: new_waiter.then_some(WorkAnnouncement::NeedsInput),+ announce: (!new_waiting_panes.is_empty()).then_some(WorkAnnouncement::NeedsInput),+ new_waiting_panes,}}WorkspaceThreadWorkStatus::Idle | WorkspaceThreadWorkStatus::FinishedUnseen => {@@ -8950,6 +9176,7 @@ impl WorkspaceThread {changed: was_running || had_attention,should_persist,announce: finished_now.then_some(WorkAnnouncement::Finished),+ new_waiting_panes: Vec::new(),}}}@@ -10096,11 +10323,12 @@ pub(crate) fn native_pane_work_status(pane: &dyn mux::pane::Pane) -> WorkspaceThWorkspaceThreadWorkStatus::Idle}-fn scan_workspace_work_status(workspace: &str) -> (WorkspaceThreadWorkStatus, Vec<PaneId>) {+fn scan_workspace_work_status(+ workspace: &str,+) -> (WorkspaceThreadWorkStatus, Vec<(PaneId, WorkMoment)>) {let mux = Mux::get();let mut running = false;- // Which panes are waiting, not just whether any is: a pane newly- // joining this set is a fresh question and earns its own ring.+ // Keep the kind too: the same pane can go straight from input to error.let mut waiting_panes = Vec::new();let agents_enabled = crate::agent_status::enabled();for window_id in mux.iter_windows_in_workspace(workspace) {@@ -10114,12 +10342,26 @@ fn scan_workspace_work_status(workspace: &str) -> (WorkspaceThreadWorkStatus, Vefor tab in tabs {for pane in tab.iter_all_panes() {- let observed = agents_enabled+ let agent = agents_enabled.then(|| crate::agent_status::agent_work_status(pane.as_ref()))- .flatten()- .unwrap_or_else(|| native_pane_work_status(pane.as_ref()));+ .flatten();+ let observed = agent.unwrap_or_else(|| native_pane_work_status(pane.as_ref()));match observed {- WorkspaceThreadWorkStatus::NeedsAttention => waiting_panes.push(pane.pane_id()),+ WorkspaceThreadWorkStatus::NeedsAttention => {+ // Native NeedsAttention only comes from Error.+ // Keep that observation even if progress changes+ // before the next read of the pane.+ let errored = agent.is_none()+ || pane.agent_status().is_some_and(|status| {+ status.state == crate::agent_status::AgentState::Error+ });+ let moment = if errored {+ WorkMoment::Error+ } else {+ WorkMoment::NeedsInput+ };+ waiting_panes.push((pane.pane_id(), moment));+ }WorkspaceThreadWorkStatus::Running => running = true,_ => {}}@@ -12314,8 +12556,7 @@ mod tests {/// Typing an answer into an agent's question must not ring per key:/// each keypress acknowledges the active workspace and the next scan- /// re-observes the same still-waiting pane. Only a pane newly joining- /// the waiting set may ring.+ /// re-observes the same still-waiting pane and attention kind.#[test]fn acknowledged_waiting_episode_relights_silently() {let mut thread = WorkspaceThread::new(@@ -12323,7 +12564,8 @@ mod tests {"main".to_string(),Some("workspace-1".to_string()),);- let first = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[7]);+ let waiting = [(7, WorkMoment::NeedsInput)];+ let first = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &waiting);assert_eq!(first.announce, Some(WorkAnnouncement::NeedsInput));// Keypress: acknowledge clears the badge and marks the episode.if thread.work_needs_attention {@@ -12331,12 +12573,12 @@ mod tests {}thread.work_needs_attention = false;// The agent is still waiting: badge relights, sound stays quiet.- let relight = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[7]);+ let relight = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &waiting);assert!(relight.changed);assert_eq!(relight.announce, None, "same pane must not re-ring");// The question is answered and a new one appears: rings again.thread.observe_work_status(WorkspaceThreadWorkStatus::Running, &[]);- let next = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[7]);+ let next = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &waiting);assert_eq!(next.announce, Some(WorkAnnouncement::NeedsInput));}@@ -12349,20 +12591,22 @@ mod tests {"main".to_string(),Some("workspace-1".to_string()),);- let a = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[1]);+ let first = [(1, WorkMoment::NeedsInput)];+ let both = [(1, WorkMoment::NeedsInput), (2, WorkMoment::NeedsInput)];+ let a = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &first);assert_eq!(a.announce, Some(WorkAnnouncement::NeedsInput));// A second agent starts waiting while the first still is.- let b = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[1, 2]);+ let b = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &both);assert_eq!(b.announce, Some(WorkAnnouncement::NeedsInput));// Both merely still waiting: quiet.- let held = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[1, 2]);+ let held = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &both);assert_eq!(held.announce, None);// One is answered while the other still waits: quiet.- let fewer = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[2]);+ let fewer = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &both[1..]);assert_eq!(fewer.announce, None);// The answered one asks a new question: it left and re-joined the// waiting set, so it rings again.- let again = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &[1, 2]);+ let again = thread.observe_work_status(WorkspaceThreadWorkStatus::NeedsAttention, &both);assert_eq!(again.announce, Some(WorkAnnouncement::NeedsInput));}@@ -12428,8 +12672,8 @@ mod tests {) -> Option<WorkAnnouncement> {// NeedsAttention always arrives with the waiting panes in// production (the status IS "some pane waits"); mirror that.- let waiting: &[PaneId] = match status {- WorkspaceThreadWorkStatus::NeedsAttention => &[1],+ let waiting: &[(PaneId, WorkMoment)] = match status {+ WorkspaceThreadWorkStatus::NeedsAttention => &[(1, WorkMoment::NeedsInput)],_ => &[],};store@@ -12585,6 +12829,154 @@ mod tests {);}+ #[test]+ fn the_dock_counts_each_matching_thread_once_even_with_both_attention_kinds() {+ use WorkspaceThreadWorkStatus as Status;+ let attention = collect_work_moments([WorkMoment::NeedsInput, WorkMoment::Error]);+ let unseen = unseen_work_moments(Status::NeedsAttention, attention);+ assert_eq!(+ first_work_moment(unseen, |m| m == WorkMoment::NeedsInput),+ Some(WorkMoment::NeedsInput)+ );+ assert_eq!(+ first_work_moment(unseen, |m| m == WorkMoment::Error),+ Some(WorkMoment::Error)+ );+ assert_eq!(+ first_work_moment(unseen, |_| true),+ Some(WorkMoment::NeedsInput)+ );+ assert_eq!(+ first_work_moment(+ unseen_work_moments(Status::FinishedUnseen, attention),+ |_| true+ ),+ Some(WorkMoment::Finished)+ );+ assert_eq!(+ first_work_moment(unseen_work_moments(Status::Running, attention), |_| true),+ None+ );+ assert_eq!(+ first_work_moment(unseen_work_moments(Status::Idle, attention), |_| true),+ None+ );+ }++ #[test]+ fn an_old_error_does_not_reclassify_a_new_input_request() {+ use WorkspaceThreadWorkStatus as Status;+ let mut thread = WorkspaceThread::new("project-1".into(), "work".into(), None);+ let waiting = [+ (1, attention_moment(None, false, &Progress::Error(100)).unwrap()),+ (+ 2,+ attention_moment(Some(Status::NeedsAttention), false, &Progress::Error(100))+ .unwrap(),+ ),+ ];+ thread.observe_work_status(Status::NeedsAttention, &waiting[..1]);+ let change = thread.observe_work_status(Status::NeedsAttention, &waiting);+ assert_eq!(change.new_waiting_panes, vec![(2, WorkMoment::NeedsInput)]);+ let moments = work_moments(change.announce.unwrap(), &change.new_waiting_panes);+ assert!(moments.needs_input);+ assert!(!moments.error);+ assert_eq!(+ first_work_moment(moments, |m| m == WorkMoment::NeedsInput),+ Some(WorkMoment::NeedsInput)+ );+ assert!(thread+ .observe_work_status(Status::NeedsAttention, &waiting)+ .new_waiting_panes+ .is_empty());++ assert_eq!(+ attention_moment(Some(Status::NeedsAttention), true, &Progress::None),+ Some(WorkMoment::Error)+ );+ assert_eq!(+ attention_moment(Some(Status::Idle), false, &Progress::Error(100)),+ None+ );+ }++ #[test]+ fn a_waiting_pane_changing_to_error_announces_once_with_an_error_only_filter() {+ use WorkspaceThreadWorkStatus as Status;+ let mut store = work_store_with_one_thread();+ let waiting = [(1, WorkMoment::NeedsInput)];+ let failed = [(1, WorkMoment::Error)];+ let error_only = WorkMoments {+ finished: false,+ needs_input: false,+ error: true,+ };+ let input = store+ .observe_thread_work_for_workspace("workspace-1", Status::NeedsAttention, &waiting)+ .unwrap();+ assert_eq!(+ first_work_moment(+ work_moments(input.announce.unwrap(), &input.new_waiting_panes),+ |moment| error_only.includes(moment)+ ),+ None+ );++ // Each keypress acknowledges the question, then the next scan+ // sees it still waiting. Neither sound nor a banner may replay.+ for _ in 0..3 {+ store.acknowledge_thread_work_for_workspace("workspace-1");+ let same = store+ .observe_thread_work_for_workspace("workspace-1", Status::NeedsAttention, &waiting)+ .unwrap();+ assert_eq!(same.announce, None);+ assert!(same.new_waiting_panes.is_empty());+ }++ // No Running or Idle observation separates the input and error.+ let error = store+ .observe_thread_work_for_workspace("workspace-1", Status::NeedsAttention, &failed)+ .unwrap();+ assert_eq!(error.new_waiting_panes, failed);+ let moments = work_moments(error.announce.unwrap(), &error.new_waiting_panes);+ assert_eq!(moments, error_only);+ assert_eq!(+ first_work_moment(moments, |moment| error_only.includes(moment)),+ Some(WorkMoment::Error),+ "both sound and system notification filters must see the new error"+ );+ for _ in 0..3 {+ store.acknowledge_thread_work_for_workspace("workspace-1");+ let same = store+ .observe_thread_work_for_workspace("workspace-1", Status::NeedsAttention, &failed)+ .unwrap();+ assert_eq!(same.announce, None);+ }++ // Leaving attention ends the episode, so a later error is new.+ for cleared in [Status::Running, Status::Idle] {+ store.observe_thread_work_for_workspace("workspace-1", cleared, &[]);+ let next = store+ .observe_thread_work_for_workspace("workspace-1", Status::NeedsAttention, &failed)+ .unwrap();+ assert_eq!(next.announce, Some(WorkAnnouncement::NeedsInput));+ assert_eq!(next.new_waiting_panes, failed);+ }+ }++ #[test]+ fn a_failed_build_reported_by_progress_is_an_error() {+ use WorkspaceThreadWorkStatus as Status;+ assert!(reports_native_error(None, &Progress::Error(100)));+ assert!(!reports_native_error(None, &Progress::Percentage(40)));+ assert!(!reports_native_error(None, &Progress::None));+ // An agent's own state decides for its pane.+ assert!(!reports_native_error(+ Some(Status::NeedsAttention),+ &Progress::Error(100)+ ));+ }+#[test]fn pending_notifications_list_attention_first_and_skip_idle_running() {let mut store = test_store();