Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

feat(optimus): mute key: stop listening, keep working (0.4.4)

Salman Qureshidb70347dbda5
diff --git a/plugins/optimus/README.md b/plugins/optimus/README.md
index 2637322d..40c0677d 100644
--- a/plugins/optimus/README.md
+++ b/plugins/optimus/README.md
@@ -26,6 +26,7 @@ Change any of it later in `/plugins optimus`.
- **Chat:** ask Mercury in any chat (TUI, dashboard, WhatsApp, Telegram): "look at my screen", "open Safari and search for…".
- **Listening:** press the talk key (you hear a rising chime), talk, and Mercury answers out loud while it works on your screen, saying each step as it happens. A soft tick means it's still working.
- **The talk key:** while Optimus is working it's the **stop button** (everything halts, you keep talking); while Mercury is speaking it interrupts; when all is quiet it ends the session (falling chime).
+- **Mute:** Control+Option+Shift+M (or say "mute") stops listening while Mercury keeps working and talking; nothing you say is sent. Press it again, or the talk key, to unmute. The status bar shows 🔇.
- **Saying "stop"** ("cancel", "ruko", "bas") halts every action and the task at once; **"bye"** does the same and ends the session. Silence for 60 seconds ends it too.
- Links and details go to your Mercury chat. Approvals are asked out loud.
- With speakers, the mic is muted while Mercury talks so it doesn't hear itself. With headphones, turn on "I use headphones" in `/plugins optimus` → 🎙 Voice to interrupt just by talking.
diff --git a/plugins/optimus/companion/Cargo.lock b/plugins/optimus/companion/Cargo.lock
index c590c693..bf8d0e97 100644
--- a/plugins/optimus/companion/Cargo.lock
+++ b/plugins/optimus/companion/Cargo.lock
@@ -1280,7 +1280,7 @@ dependencies = [
[[package]]
name = "mercury-optimus"
-version = "0.4.3"
+version = "0.4.4"
dependencies = [
"base64 0.22.1",
"core-foundation",
diff --git a/plugins/optimus/companion/Cargo.toml b/plugins/optimus/companion/Cargo.toml
index a7b93c09..fdce6f09 100644
--- a/plugins/optimus/companion/Cargo.toml
+++ b/plugins/optimus/companion/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "mercury-optimus"
-version = "0.4.3"
+version = "0.4.4"
edition = "2024"
rust-version = "1.94"
description = "Optimus: full computer control for Mercury (screen, mouse, keyboard, apps, voice)"
diff --git a/plugins/optimus/companion/src/audio.rs b/plugins/optimus/companion/src/audio.rs
index d4d9c5f7..a4d2d00d 100644
--- a/plugins/optimus/companion/src/audio.rs
+++ b/plugins/optimus/companion/src/audio.rs
@@ -52,6 +52,17 @@ impl Output {
self.busy() || (self.start.elapsed().as_millis() as u64).saturating_sub(self.last_sound.load(Ordering::Relaxed)) < ms
}
+ /// One soft low tone: "muted".
+ pub fn mute_tone(&self) {
+ let mut q = self.queue.lock().unwrap();
+ let n = (self.rate as f32 * 0.12) as usize;
+ for i in 0..n {
+ let t = i as f32 / self.rate as f32;
+ let env = (std::f32::consts::PI * i as f32 / n as f32).sin();
+ q.push_back((2.0 * std::f32::consts::PI * 440.0 * t).sin() * 0.14 * env);
+ }
+ }
+
/// A short tone: rising for "listening", falling for "stopped".
pub fn chime(&self, rising: bool) {
let mut q = self.queue.lock().unwrap();
diff --git a/plugins/optimus/companion/src/core.rs b/plugins/optimus/companion/src/core.rs
index a779c578..c55dfeeb 100644
--- a/plugins/optimus/companion/src/core.rs
+++ b/plugins/optimus/companion/src/core.rs
@@ -123,7 +123,7 @@ pub struct Shared {
/// How the talk key reads, e.g. "Control+Option+M" (empty when there's none).
pub hotkey_label: Mutex<String>,
/// Screen operations in progress, and the (listening, working) state last reported.
- working: Mutex<(u32, Option<(bool, bool)>)>,
+ working: Mutex<(u32, Option<(bool, bool, bool)>)>,
/// Steps that failed or were stopped, with when: a voice answer is checked against them.
pub failures: Mutex<Vec<(std::time::Instant, String)>>,
}
@@ -136,12 +136,15 @@ impl Shared {
/// Tell Mercury whether Optimus is listening and/or working (the TUI status bar shows it).
pub fn publish_activity(&self) {
- let listening = self.session.lock().unwrap().is_some();
+ let (listening, muted) = match self.session.lock().unwrap().as_ref() {
+ Some(s) => (true, s.is_muted()),
+ None => (false, false),
+ };
let mut w = self.working.lock().unwrap();
- let now = (listening, w.0 > 0);
+ let now = (listening, w.0 > 0, muted);
if w.1 != Some(now) {
w.1 = Some(now);
- self.out.notify("mercury/channel/activity", json!({ "listening": now.0, "working": now.1 }));
+ self.out.notify("mercury/channel/activity", json!({ "listening": now.0, "working": now.1, "muted": now.2 }));
}
}
}
@@ -294,7 +297,11 @@ fn start_hotkey(shared: &Arc<Shared>) {
Ok(()) => {
*shared.hotkey_label.lock().unwrap() = label.clone();
log(format!("press {label} to talk"));
- status(format!("Press {label} to talk; press it again to stop."));
+ let mute = start_mute_key(shared);
+ status(match mute {
+ Some(m) => format!("Press {label} to talk; press it again to stop. {m} mutes."),
+ None => format!("Press {label} to talk; press it again to stop."),
+ });
}
Err(e) => {
log(format!("talk key {label}: {e}"));
@@ -303,6 +310,31 @@ fn start_hotkey(shared: &Arc<Shared>) {
}
}
+/// The mute key (default ctrl+alt+shift+m): stop listening, keep working.
+fn start_mute_key(shared: &Arc<Shared>) -> Option<String> {
+ let spec = settings().get("muteHotkey").and_then(Value::as_str).filter(|s| !s.trim().is_empty()).unwrap_or("ctrl+alt+shift+m").to_string();
+ let hk = match crate::hotkey::parse(&spec) {
+ Ok(h) => h,
+ Err(e) => {
+ log(format!("mute key: {e}"));
+ return None;
+ }
+ };
+ let label = hk.to_string();
+ let sh = shared.clone();
+ match crate::hotkey::listen(hk, move || {
+ if let Some(s) = sh.session.lock().unwrap().as_ref() {
+ s.toggle_mute();
+ }
+ }) {
+ Ok(()) => Some(label),
+ Err(e) => {
+ log(format!("mute key {label}: {e}"));
+ None
+ }
+ }
+}
+
fn on_mercury(shared: &Arc<Shared>, msg: &Value) {
// A reply to one of our requests.
if let Some(id) = msg.get("id").and_then(Value::as_str) {
diff --git a/plugins/optimus/companion/src/hotkey.rs b/plugins/optimus/companion/src/hotkey.rs
index f195290f..9c8d1706 100644
--- a/plugins/optimus/companion/src/hotkey.rs
+++ b/plugins/optimus/companion/src/hotkey.rs
@@ -92,7 +92,7 @@ pub fn parse(spec: &str) -> Result<Hotkey, String> {
pub fn listen(hk: Hotkey, on_press: impl Fn() + Send + 'static) -> Result<(), String> {
let (tx, rx) = std::sync::mpsc::channel::<Result<(), String>>();
std::thread::Builder::new()
- .name("optimus-hotkey".into())
+ .name(format!("optimus-hotkey-{}", hk.key))
.spawn(move || platform::run(hk, on_press, tx))
.map_err(|e| e.to_string())?;
rx.recv_timeout(std::time::Duration::from_secs(5)).unwrap_or_else(|_| Err("the hotkey listener didn't start".into()))
@@ -109,7 +109,6 @@ mod platform {
fn CGEventTapEnable(tap: *mut std::ffi::c_void, enable: bool);
}
- static TAP: AtomicPtr<std::ffi::c_void> = AtomicPtr::new(std::ptr::null_mut());
fn keycode(key: &str) -> Option<i64> {
let k = match key {
@@ -131,6 +130,9 @@ mod platform {
return;
};
let want = hk.mods;
+ // Each listener (talk, mute) has its own tap, re-enabled if macOS pauses it.
+ let me = std::sync::Arc::new(AtomicPtr::<std::ffi::c_void>::new(std::ptr::null_mut()));
+ let me2 = me.clone();
let tap = CGEventTap::new(
CGEventTapLocation::Session,
CGEventTapPlacement::HeadInsertEventTap,
@@ -138,7 +140,7 @@ mod platform {
vec![CGEventType::KeyDown],
move |_proxy, etype, event| {
if matches!(etype, CGEventType::TapDisabledByTimeout | CGEventType::TapDisabledByUserInput) {
- let t = TAP.load(Ordering::Relaxed);
+ let t = me2.load(Ordering::Relaxed);
if !t.is_null() {
unsafe { CGEventTapEnable(t, true) };
}
@@ -166,7 +168,7 @@ mod platform {
);
match tap {
Ok(tap) => unsafe {
- TAP.store(tap.mach_port.as_concrete_TypeRef() as *mut std::ffi::c_void, Ordering::Relaxed);
+ me.store(tap.mach_port.as_concrete_TypeRef() as *mut std::ffi::c_void, Ordering::Relaxed);
let Ok(source) = tap.mach_port.create_runloop_source(0) else {
let _ = ready.send(Err("couldn't attach the hotkey listener".into()));
return;
diff --git a/plugins/optimus/companion/src/voice.rs b/plugins/optimus/companion/src/voice.rs
index 39b2466b..aa9212cd 100644
--- a/plugins/optimus/companion/src/voice.rs
+++ b/plugins/optimus/companion/src/voice.rs
@@ -30,10 +30,13 @@ pub enum Ctl {
Stop,
/// What Mercury is doing on the screen right now, to say as it happens.
Narrate(String),
+ /// The mute key: stop (or start again) listening, without stopping any work.
+ Mute,
}
pub struct SessionCtl {
tx: mpsc::UnboundedSender<Ctl>,
+ muted: Arc<std::sync::atomic::AtomicBool>,
}
impl SessionCtl {
@@ -43,6 +46,12 @@ impl SessionCtl {
pub fn narrate(&self, line: String) {
let _ = self.tx.send(Ctl::Narrate(line));
}
+ pub fn toggle_mute(&self) {
+ let _ = self.tx.send(Ctl::Mute);
+ }
+ pub fn is_muted(&self) -> bool {
+ self.muted.load(std::sync::atomic::Ordering::Relaxed)
+ }
}
/// The talk key was pressed (or the `listen` tool called).
@@ -61,13 +70,14 @@ pub async fn press(sh: Arc<Shared>, from_tool: bool) -> Result<String, String> {
return Err("listening mode is off: choose Listening or Both in /plugins optimus".into());
}
let (tx, rx) = mpsc::unbounded_channel::<Ctl>();
+ let muted = Arc::new(std::sync::atomic::AtomicBool::new(false));
{
// Claim the slot first, so a double press can't start two sessions.
let mut live = sh.session.lock().unwrap();
if live.is_some() {
return Ok(String::new());
}
- *live = Some(SessionCtl { tx });
+ *live = Some(SessionCtl { tx, muted: muted.clone() });
}
crate::core::clear_halt();
let call_id = format!("desk-{}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_millis()).unwrap_or(0));
@@ -100,7 +110,7 @@ pub async fn press(sh: Arc<Shared>, from_tool: bool) -> Result<String, String> {
sh.publish_activity();
let sh2 = sh.clone();
tokio::spawn(async move {
- run_session(sh2.clone(), audio, rx, call_id, instructions).await;
+ run_session(sh2.clone(), audio, rx, muted, call_id, instructions).await;
*sh2.session.lock().unwrap() = None;
sh2.publish_activity();
});
@@ -149,13 +159,13 @@ fn tools() -> Value {
])
}
-async fn run_session(sh: Arc<Shared>, audio: Audio, ctl: mpsc::UnboundedReceiver<Ctl>, call_id: String, instructions: String) {
+async fn run_session(sh: Arc<Shared>, audio: Audio, ctl: mpsc::UnboundedReceiver<Ctl>, muted: Arc<std::sync::atomic::AtomicBool>, call_id: String, instructions: String) {
let started = Instant::now();
let mut transcript: Vec<Value> = Vec::new();
audio.out.chime(true);
let engine = links::engine(&settings());
log(format!("session {call_id} starting with {engine}"));
- let outcome = match bridge(&sh, audio, ctl, &call_id, &instructions, &mut transcript).await {
+ let outcome = match bridge(&sh, audio, ctl, &muted, &call_id, &instructions, &mut transcript).await {
Ok(()) => "completed".to_string(),
Err(e) => {
log(format!("session {call_id} ({engine}) failed: {e}"));
@@ -182,6 +192,7 @@ async fn bridge(
sh: &Arc<Shared>,
mut audio: Audio,
mut ctl: mpsc::UnboundedReceiver<Ctl>,
+ muted: &Arc<std::sync::atomic::AtomicBool>,
call_id: &str,
instructions: &str,
transcript: &mut Vec<Value>,
@@ -284,6 +295,16 @@ async fn bridge(
speak_narration(&link, brain, &mut narration, &mut responding);
}
}
+ Some(Ctl::Mute) => {
+ let now = !muted.load(std::sync::atomic::Ordering::Relaxed);
+ set_muted(sh, muted, &out, now, &call_id);
+ last_activity = Instant::now();
+ }
+ Some(Ctl::Press) if muted.load(std::sync::atomic::Ordering::Relaxed) => {
+ // Muted: the talk key unmutes rather than stopping anything.
+ set_muted(sh, muted, &out, false, &call_id);
+ last_activity = Instant::now();
+ }
Some(Ctl::Press) => {
if busy_working(&pending) {
// While it's working, the key is the stop button: everything halts, the session stays.
@@ -306,6 +327,8 @@ async fn bridge(
},
frame = mic.recv() => {
let Some(frame) = frame else { break Err("the microphone stopped".to_string()) };
+ // Muted: nothing the owner says is sent anywhere.
+ if muted.load(std::sync::atomic::Ordering::Relaxed) { continue; }
// With speakers, the mic would hear Mercury: send silence while it talks.
let muted = !barge_in && out.recently_audible(350);
link.send(LinkCmd::Audio(if muted { silence.clone() } else { frame }));
@@ -330,6 +353,7 @@ async fn bridge(
continue;
}
if responding || out.busy() { last_activity = Instant::now(); continue; }
+ if muted.load(std::sync::atomic::Ordering::Relaxed) { last_activity = Instant::now(); }
if idle_stop > 0.0
&& last_activity.elapsed().as_secs_f64() >= idle_stop
&& last_narrated.elapsed().as_secs_f64() >= idle_stop
@@ -420,6 +444,10 @@ async fn bridge(
transcript.push(json!({ "role": "owner", "text": t.clone() }));
user_said.push((Instant::now(), t.clone()));
if user_said.len() > 20 { user_said.remove(0); }
+ if is_mute(&t) {
+ set_muted(sh, muted, &out, true, &call_id);
+ continue;
+ }
if is_stop(&t) && verifying.is_none() && awaiting.is_none() {
// "Stop" / "cancel" / "ruko": halt everything at once.
stop_all(&pending);
@@ -527,6 +555,19 @@ fn honest(brain: Brain, answer: String, failed: &[String]) -> String {
}
}
+fn set_muted(sh: &Arc<Shared>, muted: &Arc<std::sync::atomic::AtomicBool>, out: &Arc<audio::Output>, on: bool, call_id: &str) {
+ muted.store(on, std::sync::atomic::Ordering::Relaxed);
+ if on { out.mute_tone() } else { out.chime(true) }
+ log(format!("{call_id}: {}", if on { "muted" } else { "unmuted" }));
+ sh.publish_activity();
+}
+
+/// "Mute" / "mute yourself" / "go on mute".
+fn is_mute(t: &str) -> bool {
+ let t = format!(" {} ", t.to_lowercase().replace(|c: char| !c.is_alphanumeric() && !c.is_whitespace() && (c as u32) < 128, " "));
+ t.split_whitespace().count() <= 4 && [" mute ", " go on mute ", " mute yourself ", " mute karo "].iter().any(|w| t.contains(w)) && !t.contains(" unmute ")
+}
+
fn say_stopped(link: &Link, brain: Brain) {
match brain {
Brain::Voice => link.send(LinkCmd::Instruct("[The user stopped everything, not said by the user] All of Mercury's actions have been stopped. Say only: 'Stopped.' Then wait.".into())),
@@ -642,6 +683,14 @@ mod tests {
assert_eq!(honest(Brain::Mercury, "The click failed.".into(), &["act: FAILED".into()]), "The click failed.");
}
+ #[test]
+ fn mute_words() {
+ assert!(is_mute("Mute."));
+ assert!(is_mute("mute yourself"));
+ assert!(!is_mute("unmute"));
+ assert!(!is_mute("how do I mute notifications on my phone"));
+ }
+
#[test]
fn stop_words() {
assert!(is_stop("Stop!"));
diff --git a/plugins/optimus/mercury-plugin.template.json b/plugins/optimus/mercury-plugin.template.json
index f0988ba1..9e4911bf 100644
--- a/plugins/optimus/mercury-plugin.template.json
+++ b/plugins/optimus/mercury-plugin.template.json
@@ -2,7 +2,7 @@
"manifestVersion": 1,
"id": "optimus",
"name": "Optimus",
- "version": "0.4.3",
+ "version": "0.4.4",
"description": "Mercury uses your computer like a person: sees the screen, moves the mouse, types and opens apps, by chat or out loud with a talk key. macOS, Windows and Linux. Asks before anything that submits, sends, pays or deletes.",
"kind": "out-of-process",
"author": "Cosmic Stack",
@@ -184,6 +184,18 @@
]
}
},
+ "muteHotkey": {
+ "type": "string",
+ "default": "ctrl+alt+shift+m",
+ "label": "Key to mute and unmute",
+ "description": "While talking: Optimus stops listening (nothing you say is sent anywhere) but keeps working and still speaks. Press again, or press the talk key, to unmute. Saying \"mute\" also mutes.",
+ "when": {
+ "mode": [
+ "voice",
+ "both"
+ ]
+ }
+ },
"bargeIn": {
"type": "boolean",
"default": false,
diff --git a/src/plugins/channel-bridge.ts b/src/plugins/channel-bridge.ts
index 19321451..5ef82329 100644
--- a/src/plugins/channel-bridge.ts
+++ b/src/plugins/channel-bridge.ts
@@ -397,7 +397,7 @@ export class PluginChannel extends BaseChannel {
/** Plugin API 1.2: what a desktop plugin is doing right now, for the status bar. */
private onActivity(params: unknown): void {
const p = (params ?? {}) as Record<string, unknown>;
- desktopActivityHook?.(activityLabel(this.manifest.name, p.listening === true, p.working === true));
+ desktopActivityHook?.(activityLabel(this.manifest.name, p.listening === true, p.working === true, p.muted === true));
}
private onCallEnded(params: unknown): void {
@@ -835,8 +835,9 @@ export function setDesktopActivityHook(fn: ((label: string | null) => void) | nu
desktopActivityHook = fn;
}
-/** "🎙 Optimus listening", "🖱 Optimus working", both, or null when idle. */
-export function activityLabel(name: string, listening: boolean, working: boolean): string | null {
+/** "🎙 Optimus listening", "🖱 Optimus working", "🔇 Optimus muted", combinations, or null when idle. */
+export function activityLabel(name: string, listening: boolean, working: boolean, muted = false): string | null {
+ if (listening && muted) return working ? `🔇🖱 ${name} working (muted)` : `🔇 ${name} muted`;
if (listening && working) return `🎙🖱 ${name} working`;
if (working) return `🖱 ${name} working`;
if (listening) return `🎙 ${name} listening`;
diff --git a/src/plugins/channel.test.ts b/src/plugins/channel.test.ts
index 70b3cfa1..e4b71ad1 100644
--- a/src/plugins/channel.test.ts
+++ b/src/plugins/channel.test.ts
@@ -558,6 +558,8 @@ describe('plugin channels (plugin API 1.1)', () => {
setDesktopActivityHook(null);
}
expect(activityLabel('Optimus', false, true)).toBe('🖱 Optimus working');
+ expect(activityLabel('Optimus', true, false, true)).toBe('🔇 Optimus muted');
+ expect(activityLabel('Optimus', true, true, true)).toBe('🔇🖱 Optimus working (muted)');
});
it('"stop" on the call ends the work it started, and its pending approvals', async () => {