Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(computer): step the Dot aside while the agent acts

Alan Buscagliac48afb553882
diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs
index 77e12ce..d4ad26f 100644
--- a/apps/desktop/src-tauri/build.rs
+++ b/apps/desktop/src-tauri/build.rs
@@ -16,6 +16,7 @@ const COMMANDS: &[&str] = &[
"computer_stop",
"computer_status",
"computer_set_yolo",
+ "computer_working_ready",
"voice_status",
"voice_start",
"voice_stop",
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index 3bcd2a0..775ed23 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -54,9 +54,9 @@
},
{
"identifier": "glow",
- "description": "What the computer-control glow overlay (S28) may call: listening to the glow and session events, nothing else.",
+ "description": "What the computer-control glow overlay (S28) may call: listening to the glow, working, and session events, and acknowledging that the working rings are on screen; nothing else.",
"windows": ["glow"],
- "permissions": ["core:event:allow-listen", "core:event:allow-unlisten"]
+ "permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "allow-computer-working-ready"]
}
]
}
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/computer_working_ready.toml b/apps/desktop/src-tauri/permissions/autogenerated/computer_working_ready.toml
new file mode 100644
index 0000000..173b5f0
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/computer_working_ready.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-computer-working-ready"
+description = "Enables the computer_working_ready command without any pre-configured scope."
+commands.allow = ["computer_working_ready"]
+
+[[permission]]
+identifier = "deny-computer-working-ready"
+description = "Denies the computer_working_ready command without any pre-configured scope."
+commands.deny = ["computer_working_ready"]
diff --git a/apps/desktop/src-tauri/src/computer/app.rs b/apps/desktop/src-tauri/src/computer/app.rs
index f74c2ac..79d0da8 100644
--- a/apps/desktop/src-tauri/src/computer/app.rs
+++ b/apps/desktop/src-tauri/src/computer/app.rs
@@ -7,10 +7,17 @@
//! active and out when it ends. The helper's marks reach it through a channel, so the helper
//! never waits on the overlay; a thread of its own looks up the display (and, for keys, the
//! focused element), moves the overlay over that display, and emits `computer://glow`.
+//!
+//! The working rings (S1, S2, S5): the same thread covers the display under the pointer, orders
+//! the overlay in, and emits `computer://working` for each prepared call; the overlay answers
+//! with `computer_working_ready`, and the end of the call or of the session clears the rings.
use super::control::Control;
use super::server::Endpoint;
use super::session::{Reason, StateEvent};
+use super::working::Windows;
+#[cfg(target_os = "macos")]
+use super::working::{MainThread, Rings, Task, Working, WorkingEvent, READY_TIMEOUT, WORKING_EVENT};
use super::{Clock, PermissionKind, Permissions, SystemClock};
use crate::alert::Choice;
use std::sync::Arc;
@@ -39,13 +46,59 @@ pub struct Computer {
endpoint: Option<Endpoint>,
#[cfg(target_os = "macos")]
desktop: Arc<dyn super::Desktop>,
+ #[cfg(target_os = "macos")]
+ working: Arc<Working>,
}
-/// What the overlay thread hears: the session started or ended, or the agent acted.
+/// What the overlay thread hears: the session started or ended, the agent acted, or a call
+/// starts (answered once the rings were told to draw, or why not) or ends its working rings.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
enum Overlay {
Session(bool),
Mark(super::glow::Mark),
+ Working { operation: u64, reply: std::sync::mpsc::Sender<Result<(), String>> },
+ WorkingEnd(u64),
+}
+
+/// How long the overlay thread waits for the main thread to order the overlay in.
+#[cfg(target_os = "macos")]
+const OVERLAY_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(1);
+
+/// The overlay's working rings, through the overlay thread.
+#[cfg(target_os = "macos")]
+struct OverlayRings(std::sync::mpsc::Sender<Overlay>);
+
+#[cfg(target_os = "macos")]
+impl Rings for OverlayRings {
+ fn show(&self, operation: u64) -> Result<(), String> {
+ let (reply, answer) = std::sync::mpsc::channel();
+ self.0.send(Overlay::Working { operation, reply }).map_err(|_| "the glow is unavailable".to_string())?;
+ answer.recv_timeout(READY_TIMEOUT).map_err(|_| "the glow did not answer in time".to_string())?
+ }
+
+ fn end(&self, operation: u64) {
+ let _ = self.0.send(Overlay::WorkingEnd(operation));
+ }
+}
+
+#[cfg(target_os = "macos")]
+struct AppMainThread(AppHandle);
+
+#[cfg(target_os = "macos")]
+impl MainThread for AppMainThread {
+ fn run(&self, task: Task) -> Result<(), String> {
+ self.0.run_on_main_thread(task).map_err(|error| error.to_string())
+ }
+}
+
+/// Orders one of the app's windows in without making it key or activating the app: the Dot and
+/// the panel once a computer-control call ends (S5). Main thread only.
+#[cfg(target_os = "macos")]
+pub fn show_without_focus(window: &tauri::WebviewWindow) -> Result<(), String> {
+ let ns_window = window.ns_window().map_err(|error| error.to_string())?;
+ // SAFETY: on the main thread (the caller's contract), with the window's live NSWindow.
+ unsafe { super::macos::order_window(ns_window, true) };
+ Ok(())
}
impl Computer {
@@ -57,9 +110,27 @@ impl Computer {
}
/// Creates the session and, on macOS, starts the MCP helper, the timeout watcher, and the
-/// glow overlay. Runs in the app's setup, on the main thread.
-pub fn start(app: &AppHandle) -> Computer {
+/// glow overlay. `windows` are the Dot and the panel, hidden during each call (S1). Runs in the
+/// app's setup, on the main thread.
+pub fn start(app: &AppHandle, windows: Arc<dyn Windows>) -> Computer {
let (overlay, marks) = std::sync::mpsc::channel::<Overlay>();
+ #[cfg(target_os = "macos")]
+ let working = Arc::new(Working::new(
+ windows,
+ Arc::new(OverlayRings(overlay.clone())),
+ Arc::new(AppMainThread(app.clone())),
+ READY_TIMEOUT,
+ ));
+ #[cfg(target_os = "macos")]
+ let session_ended = {
+ let working = working.clone();
+ move || working.session_ended()
+ };
+ #[cfg(not(target_os = "macos"))]
+ let session_ended = {
+ drop(windows);
+ || {}
+ };
let events = app.clone();
let session = overlay.clone();
let control = Arc::new(Control::new(move |event: &StateEvent| {
@@ -70,6 +141,10 @@ pub fn start(app: &AppHandle) -> Computer {
let _ = item.0.set_checked(event.yolo);
}
let _ = session.send(Overlay::Session(event.active));
+ // Stop, panic, or the timeout: the call under way gives the Dot and the panel back now.
+ if !event.active {
+ session_ended();
+ }
}));
#[cfg(target_os = "macos")]
{
@@ -78,15 +153,17 @@ pub fn start(app: &AppHandle) -> Computer {
let glow = move |mark| {
let _ = overlay.send(Overlay::Mark(mark));
};
- let endpoint = start_helper(app, control.clone(), desktop.clone(), glow)
+ let endpoint = start_helper(app, control.clone(), desktop.clone(), glow, working.clone())
.map_err(|error| eprintln!("gentle-dot: computer control is unavailable: {error}"))
.ok();
watch_timeout(control.clone());
+ // Without the overlay, `marks` is dropped: no rings can show, so every call that
+ // captures or acts fails before doing anything (S5).
match build_overlay(app, &number) {
- Ok(window) => run_overlay(app.clone(), window, number, control.clone(), marks),
+ Ok(window) => run_overlay(app.clone(), window, number, control.clone(), working.clone(), marks),
Err(error) => eprintln!("gentle-dot: the computer-control glow is unavailable: {error}"),
}
- Computer { control, endpoint, desktop }
+ Computer { control, endpoint, desktop, working }
}
#[cfg(not(target_os = "macos"))]
{
@@ -101,6 +178,7 @@ fn start_helper(
control: Arc<Control>,
desktop: Arc<dyn super::Desktop>,
glow: impl Fn(super::glow::Mark) + Send + Sync + 'static,
+ working: Arc<Working>,
) -> std::io::Result<Endpoint> {
let token = super::server::new_token();
let helper = super::mcp::Helper::new(
@@ -111,7 +189,8 @@ fn start_helper(
token.clone(),
std::process::id() as i32,
)
- .with_glow(glow);
+ .with_glow(glow)
+ .with_working(working);
super::server::start(Arc::new(helper), token)
}
@@ -151,41 +230,104 @@ fn build_overlay(
Ok((window, NsWindow(ns_window as usize)))
}
-/// Orders the overlay in or out on the main thread and records its window number.
+/// Orders the overlay in or out on the main thread and records its window number. The receiver
+/// hears once that happened.
#[cfg(target_os = "macos")]
-fn order_overlay(app: &AppHandle, ns_window: NsWindow, number: &Arc<std::sync::atomic::AtomicU32>, visible: bool) {
+fn order_overlay(
+ app: &AppHandle,
+ ns_window: NsWindow,
+ number: &Arc<std::sync::atomic::AtomicU32>,
+ visible: bool,
+) -> Result<std::sync::mpsc::Receiver<()>, String> {
let number = number.clone();
- let ordered = app.run_on_main_thread(move || {
+ let (done, ordered) = std::sync::mpsc::channel();
+ let queued = app.run_on_main_thread(move || {
// SAFETY: on the main thread, with the overlay's live NSWindow.
let n = unsafe { super::macos::order_overlay(ns_window.0 as *mut std::ffi::c_void, visible) };
if n != 0 {
number.store(n, std::sync::atomic::Ordering::SeqCst);
}
+ let _ = done.send(());
});
- if let Err(error) = ordered {
+ queued.map(|()| ordered).map_err(|error| {
eprintln!("gentle-dot: cannot show or hide the glow: {error}");
+ error.to_string()
+ })
+}
+
+/// Moves the overlay over `display` unless it already covers it.
+#[cfg(target_os = "macos")]
+fn cover(window: &tauri::WebviewWindow, covering: &mut Option<super::glow::Frame>, display: super::glow::Frame) {
+ use tauri::{LogicalPosition, LogicalSize};
+ if *covering != Some(display) {
+ let _ = window.set_position(LogicalPosition::new(display.x, display.y));
+ let _ = window.set_size(LogicalSize::new(display.width, display.height));
+ *covering = Some(display);
}
}
-/// The overlay's own thread: follows the session and draws each mark while it lasts.
+#[cfg(target_os = "macos")]
+fn emit_working(app: &AppHandle, operation: u64, active: bool) -> Result<(), String> {
+ let event = WorkingEvent { active, operation_id: operation };
+ app.emit_to(GLOW_WINDOW, WORKING_EVENT, event).map_err(|error| error.to_string())
+}
+
+/// The overlay's own thread: follows the session, draws each mark while it lasts, and shows the
+/// working rings of the call under way (`drawing`).
#[cfg(target_os = "macos")]
fn run_overlay(
app: AppHandle,
(window, ns_window): (tauri::WebviewWindow, NsWindow),
number: Arc<std::sync::atomic::AtomicU32>,
control: Arc<Control>,
+ working: Arc<Working>,
marks: std::sync::mpsc::Receiver<Overlay>,
) {
- use tauri::{LogicalPosition, LogicalSize};
let spawned = std::thread::Builder::new().name("computer-glow".into()).spawn(move || {
- let (mut shown, mut covering) = (false, None);
+ let (mut shown, mut covering, mut drawing) = (false, None, None);
for message in marks {
match message {
Overlay::Session(active) => {
if active != shown {
- order_overlay(&app, ns_window, &number, active);
+ let _ = order_overlay(&app, ns_window, &number, active);
shown = active;
}
+ if let Some(operation) = drawing.take().filter(|_| !active) {
+ let _ = emit_working(&app, operation, false);
+ }
+ }
+ Overlay::Working { operation, reply } => {
+ // A start that arrives after its call or the session ended draws nothing.
+ let outcome = if !control.is_active(SystemClock.now_ms()) || !working.is_current(operation) {
+ Err("the call already ended".to_string())
+ } else {
+ let at = super::macos::pointer_location();
+ match super::macos::display_frame_at(at) {
+ None => Err("no display under the pointer".to_string()),
+ Some(display) => {
+ cover(&window, &mut covering, display);
+ let ordered = order_overlay(&app, ns_window, &number, true);
+ shown = true;
+ // The rings are drawn only once the overlay is in front.
+ ordered
+ .and_then(|done| {
+ done.recv_timeout(OVERLAY_TIMEOUT)
+ .map_err(|_| "the glow did not show in time".to_string())
+ })
+ .and_then(|()| {
+ drawing = Some(operation);
+ emit_working(&app, operation, true)
+ })
+ }
+ }
+ };
+ let _ = reply.send(outcome);
+ }
+ Overlay::WorkingEnd(operation) => {
+ if drawing == Some(operation) {
+ drawing = None;
+ let _ = emit_working(&app, operation, false);
+ }
}
Overlay::Mark(mark) => {
// A mark that arrives after Stop or panic is dropped.
@@ -195,13 +337,9 @@ fn run_overlay(
let placed =
super::glow::place(mark, super::macos::display_frame_at, super::macos::focused_frame);
let Some((display, event)) = placed else { continue };
- if covering != Some(display) {
- let _ = window.set_position(LogicalPosition::new(display.x, display.y));
- let _ = window.set_size(LogicalSize::new(display.width, display.height));
- covering = Some(display);
- }
+ cover(&window, &mut covering, display);
if !shown {
- order_overlay(&app, ns_window, &number, true);
+ let _ = order_overlay(&app, ns_window, &number, true);
shown = true;
}
if let Err(error) = app.emit_to(GLOW_WINDOW, GLOW_EVENT, event) {
@@ -264,6 +402,23 @@ pub fn computer_stop(app: AppHandle) {
stop(&app, Reason::Stopped);
}
+/// The overlay drew the working rings for `operation_id` (S5): true when that is the call under
+/// way, false when it already ended. Any window but the overlay is refused.
+#[tauri::command]
+pub fn computer_working_ready(
+ window: tauri::WebviewWindow,
+ computer: State<'_, Computer>,
+ operation_id: u64,
+) -> Result<bool, String> {
+ #[cfg(target_os = "macos")]
+ return computer.working.acknowledge(window.label(), operation_id);
+ #[cfg(not(target_os = "macos"))]
+ {
+ let _ = (window, computer, operation_id);
+ Err("Computer control is only available on macOS.".into())
+ }
+}
+
/// Turns yolo mode on after the native confirmation, or off. Blocks on the dialog, so it runs
/// off the main thread; the tray item calls it from a thread of its own.
pub fn set_yolo(app: &AppHandle, enabled: bool) -> Result<StateEvent, String> {
diff --git a/apps/desktop/src-tauri/src/computer/macos.rs b/apps/desktop/src-tauri/src/computer/macos.rs
index 1282163..b8220ba 100644
--- a/apps/desktop/src-tauri/src/computer/macos.rs
+++ b/apps/desktop/src-tauri/src/computer/macos.rs
@@ -204,7 +204,8 @@ fn text(chunk: &str) -> Result<(), String> {
Ok(())
}
-fn pointer_location() -> Point {
+/// Where the pointer is, in global points: its display is the one computer control captures.
+pub fn pointer_location() -> Point {
let event = CGEvent::new(None);
let at = CGEvent::location(event.as_deref());
Point { x: at.x, y: at.y }
@@ -368,6 +369,19 @@ pub unsafe fn prepare_overlay(ns_window: *mut c_void) -> u32 {
/// # Safety
/// `ns_window` must be a live NSWindow.
pub unsafe fn order_overlay(ns_window: *mut c_void, visible: bool) -> u32 {
+ unsafe {
+ order_window(ns_window, visible);
+ overlay_number(&*ns_window.cast::<AnyObject>())
+ }
+}
+
+/// Orders one of the app's windows in without making it key or activating the app, or orders
+/// it out: the overlay, and the Dot and panel once a computer-control call ends (S5).
+/// Main thread only.
+///
+/// # Safety
+/// `ns_window` must be a live NSWindow.
+pub unsafe fn order_window(ns_window: *mut c_void, visible: bool) {
let window = unsafe { &*ns_window.cast::<AnyObject>() };
unsafe {
if visible {
@@ -375,7 +389,6 @@ pub unsafe fn order_overlay(ns_window: *mut c_void, visible: bool) -> u32 {
} else {
let _: () = msg_send![window, orderOut: std::ptr::null::<AnyObject>()];
}
- overlay_number(window)
}
}
diff --git a/apps/desktop/src-tauri/src/computer/mcp.rs b/apps/desktop/src-tauri/src/computer/mcp.rs
index 1bfaf20..b4462ab 100644
--- a/apps/desktop/src-tauri/src/computer/mcp.rs
+++ b/apps/desktop/src-tauri/src/computer/mcp.rs
@@ -11,6 +11,11 @@
//! The glow (S28): once an action's input is posted, `perform` reports where it acted to the
//! glow sink, so a refused, declined, stopped, or failed action (or batch step) reports
//! nothing. The sink only queues the mark; it never changes a check, the order, or a result.
+//!
+//! The working rings (S1, S5): once the session is granted, every call that captures or acts
+//! (all but `list_apps`) runs prepared: the rings show and Gentle Dot's own windows are out of
+//! the way first, and they come back once the call ends, however it ends. A preparation that
+//! fails sends nothing, and a Stop during it drops the call. The guards stay as they are.
use super::blocklist::{blocked_name, blocked_reason, AppIdentity};
use super::control::Control;
@@ -19,6 +24,7 @@ use super::glow::Mark;
use super::keys::{parse_combo, KeyCombo};
use super::rate::{RateLimiter, MAX_ACTIONS_PER_SECOND};
use super::risk::{assess, Act};
+use super::working::{NoPreparation, Preparation};
use super::{Clock, Desktop, Dialogs, InputEvent, MouseButton};
use base64::Engine as _;
use serde_json::{json, Map, Value};
@@ -107,6 +113,18 @@ fn text(text: impl Into<String>) -> Value {
json!({"type": "text", "text": text.into()})
}
+/// A prepared call (S1, S5); dropping it clears the rings and shows the windows again.
+struct Prepared<'a> {
+ working: &'a dyn Preparation,
+ operation: u64,
+}
+
+impl Drop for Prepared<'_> {
+ fn drop(&mut self) {
+ self.working.finish(self.operation);
+ }
+}
+
fn lock<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}
@@ -314,6 +332,8 @@ pub struct Helper {
actions: Mutex<Option<ScreenshotGeometry>>,
/// Where an action that went through acted (S28); must return at once.
glow: Box<dyn Fn(Mark) + Send + Sync>,
+ /// The working rings around each call that captures or acts (S1, S5).
+ working: Arc<dyn Preparation>,
}
impl Helper {
@@ -335,9 +355,16 @@ impl Helper {
limiter: Mutex::new(RateLimiter::new(MAX_ACTIONS_PER_SECOND, 1000)),
actions: Mutex::new(None),
glow: Box::new(|_| {}),
+ working: Arc::new(NoPreparation),
}
}
+ /// Prepares each call that captures or acts with `working` (S1, S5).
+ pub fn with_working(mut self, working: Arc<dyn Preparation>) -> Self {
+ self.working = working;
+ self
+ }
+
/// Reports each action that went through to `glow`, which must only queue it (S28).
pub fn with_glow(mut self, glow: impl Fn(Mark) + Send + Sync + 'static) -> Self {
self.glow = Box::new(glow);
@@ -430,9 +457,26 @@ impl Helper {
}
self.control.grant(self.clock.now_ms());
}
+ // Until the call ends, however it ends, the rings show and the Dot and panel are hidden.
+ let _prepared = match call.tool {
+ Tool::ListApps => None,
+ _ => Some(self.prepare(epoch)?),
+ };
self.act(epoch, &mut latest, call)
}
+ /// Shows the working rings and hides Gentle Dot's windows (S1, S5), then checks the session
+ /// again: a Stop meanwhile drops the call. Nothing is captured or sent when this fails.
+ fn prepare(&self, epoch: u64) -> Result<Prepared<'_>, Failed> {
+ let operation = match self.working.begin() {
+ Ok(operation) => operation,
+ Err(error) => return Err(self.still_running(epoch).err().unwrap_or(error).into()),
+ };
+ let prepared = Prepared { working: self.working.as_ref(), operation };
+ self.still_running(epoch)?;
+ Ok(prepared)
+ }
+
fn check_permissions(&self, tool: &Tool) -> Result<(), String> {
if let Tool::Batch { steps } = tool {
return steps.iter().try_for_each(|(_, step)| self.check_permissions(&step.tool));
@@ -773,6 +817,48 @@ mod tests {
states: Arc<Mutex<Vec<StateEvent>>>,
/// Each glow mark (S28), with how many input events were posted when it came.
marks: Arc<Mutex<Vec<(Mark, usize)>>>,
+ working: Arc<FakeWorking>,
+ }
+
+ /// What a step of the working rings saw: screenshots taken and input events posted so far.
+ #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+ enum Step {
+ Begin { captures: usize, events: usize },
+ Finish { captures: usize, events: usize },
+ }
+
+ /// Records each preparation (S1, S5); can fail it, or run something while it is under way.
+ struct FakeWorking {
+ desktop: Arc<FakeDesktop>,
+ steps: Mutex<Vec<Step>>,
+ fails: Mutex<Option<String>>,
+ during: Mutex<Option<Box<dyn Fn() + Send + Sync>>>,
+ }
+
+ impl FakeWorking {
+ fn seen(&self) -> (usize, usize) {
+ (self.desktop.captures.load(Ordering::SeqCst), self.desktop.events().len())
+ }
+ }
+
+ impl Preparation for FakeWorking {
+ fn begin(&self) -> Result<u64, String> {
+ let (captures, events) = self.seen();
+ self.steps.lock().unwrap().push(Step::Begin { captures, events });
+ if let Some(during) = self.during.lock().unwrap().as_ref() {
+ during();
+ }
+ match self.fails.lock().unwrap().clone() {
+ Some(error) => Err(error),
+ None => Ok(7),
+ }
+ }
+
+ fn finish(&self, operation: u64) {
+ assert_eq!(operation, 7);
+ let (captures, events) = self.seen();
+ self.steps.lock().unwrap().push(Step::Finish { captures, events });
+ }
}
fn rig_with(allow: bool, confirm: bool) -> Rig {
@@ -784,13 +870,20 @@ mod tests {
let control = Arc::new(Control::new(move |event| sink.lock().unwrap().push(event.clone())));
let marks = Arc::new(Mutex::new(Vec::new()));
let (seen, posted) = (marks.clone(), desktop.clone());
+ let working = Arc::new(FakeWorking {
+ desktop: desktop.clone(),
+ steps: Mutex::new(Vec::new()),
+ fails: Mutex::new(None),
+ during: Mutex::new(None),
+ });
let helper =
Helper::new(desktop.clone(), dialogs.clone(), clock.clone(), control.clone(), TOKEN.into(), OWN_PID)
- .with_glow(move |mark| seen.lock().unwrap().push((mark, posted.events().len())));
- Rig { helper, desktop, dialogs, clock, control, states, marks }
+ .with_glow(move |mark| seen.lock().unwrap().push((mark, posted.events().len())))
+ .with_working(working.clone());
+ Rig { helper, desktop, dialogs, clock, control, states, marks, working }
}
- /// A rig whose helper has no glow sink, as before S28.
+ /// A rig whose helper has no glow sink and no working rings, as before S28.
fn rig_without_glow(allow: bool, confirm: bool) -> Rig {
let rig = rig_with(allow, confirm);
let helper = Helper::new(
@@ -1834,6 +1927,297 @@ mod tests {
assert_eq!(*with.dialogs.confirmations.lock().unwrap(), *without.dialogs.confirmations.lock().unwrap());
assert_eq!(with.clock.now_ms(), without.clock.now_ms());
assert!(without.marks.lock().unwrap().is_empty());
+ // The rig with the glow also prepares every call; the rig without prepares none.
+ assert!(!with.working.steps.lock().unwrap().is_empty());
}
}
+
+ // --- The working rings (S1, S5) ---
+
+ fn steps(rig: &Rig) -> Vec<Step> {
+ std::mem::take(&mut *rig.working.steps.lock().unwrap())
+ }
+
+ #[test]
+ fn a_screenshot_is_taken_while_prepared() {
+ let rig = rig();
+ assert!(!is_error(&rig.call("screenshot", json!({}))));
+ assert_eq!(steps(&rig), [Step::Begin { captures: 0, events: 0 }, Step::Finish { captures: 1, events: 0 }]);
+ }
+
+ #[test]
+ fn an_action_and_the_screenshot_after_it_run_while_prepared() {
+ let rig = rig();
+ rig.ready();
+ steps(&rig);
+ assert!(!is_error(&rig.call("click", json!({"x": 10, "y": 10}))));
+ assert_eq!(steps(&rig), [Step::Begin { captures: 1, events: 0 }, Step::Finish { captures: 2, events: 1 }]);
+ for (name, args) in [("open_app", json!({"name": "Mail"})), ("wait", json!({"ms": 200}))] {
+ assert!(!is_error(&rig.call(name, args)), "{name}");
+ assert_eq!(steps(&rig).len(), 2, "{name}");
+ }
+ }
+
+ #[test]
+ fn a_batch_is_prepared_once_for_all_its_steps() {
+ let rig = rig();
+ rig.ready();
+ steps(&rig);
+ let steps_json = json!([
+ {"tool": "click", "x": 10, "y": 10},
+ {"tool": "type", "text": "Ana"},
+ {"tool": "key", "combo": "tab"},
+ ]);
+ assert!(!is_error(&rig.call("batch", batch(steps_json))));
+ assert_eq!(steps(&rig), [Step::Begin { captures: 1, events: 0 }, Step::Finish { captures: 2, events: 3 }]);
+ }
+
+ #[test]
+ fn list_apps_and_calls_refused_before_the_session_are_never_prepared() {
+ let rig = rig();
+ assert!(!is_error(&rig.call("list_apps", json!({}))));
+ assert!(is_error(&rig.call("click", json!({"x": 1}))));
+ rig.rpc("tools/call", json!({"name": "format_disk", "arguments": {}}));
+ rig.desktop.permissions.lock().unwrap().screen_recording = false;
+ assert!(is_error(&rig.call("screenshot", json!({}))));
+ assert!(steps(&rig).is_empty());
+ // A denied session grant prepares nothing.
+ let denied = rig_with(false, true);
+ assert!(is_error(&denied.call("screenshot", json!({}))));
+ assert!(is_error(&denied.call("batch", batch(json!([{"tool": "key", "combo": "tab"}])))));
+ assert!(steps(&denied).is_empty());
+ }
+
+ #[test]
+ fn a_failed_preparation_sends_nothing() {
+ let rig = rig();
+ rig.ready();
+ steps(&rig);
+ *rig.working.fails.lock().unwrap() = Some(super::super::working::UNAVAILABLE.to_string());
+ for (name, args) in [
+ ("screenshot", json!({})),
+ ("click", json!({"x": 10, "y": 10})),
+ ("batch", batch(json!([{"tool": "type", "text": "hi"}]))),
+ ] {
+ let result = rig.call(name, args);
+ assert!(is_error(&result), "{name}");
+ assert_eq!(first_text(&result), super::super::working::UNAVAILABLE, "{name}");
+ assert_eq!(image_count(&result), 0, "{name}");
+ }
+ assert!(rig.desktop.events().is_empty());
+ assert_eq!(rig.desktop.captures.load(Ordering::SeqCst), 1);
+ // A failed begin left nothing to finish.
+ assert!(steps(&rig).iter().all(|step| matches!(step, Step::Begin { .. })));
+ }
+
+ #[test]
+ fn a_stop_while_preparing_drops_the_call() {
+ let rig = rig();
+ rig.ready();
+ steps(&rig);
+ let control = rig.control.clone();
+ *rig.working.during.lock().unwrap() = Some(Box::new(move || control.end(Reason::Stopped)));
+ let result = rig.call("click", json!({"x": 10, "y": 10}));
+ assert!(is_error(&result));
+ assert_eq!(first_text(&result), STOPPED);
+ assert!(rig.desktop.events().is_empty());
+ assert_eq!(rig.desktop.captures.load(Ordering::SeqCst), 1);
+ assert_eq!(steps(&rig), [Step::Begin { captures: 1, events: 0 }, Step::Finish { captures: 1, events: 0 }]);
+ // A preparation that failed because of the Stop says the call was stopped.
+ *rig.working.during.lock().unwrap() = None;
+ rig.ready();
+ steps(&rig);
+ let control = rig.control.clone();
+ *rig.working.during.lock().unwrap() = Some(Box::new(move || control.end(Reason::Panic)));
+ *rig.working.fails.lock().unwrap() = Some(super::super::working::UNAVAILABLE.to_string());
+ assert_eq!(first_text(&rig.call("key", json!({"combo": "tab"}))), STOPPED);
+ assert!(rig.desktop.events().is_empty());
+ }
+
+ #[test]
+ fn every_prepared_call_is_finished_once_however_it_ends() {
+ let one_each = |rig: &Rig, why: &str| {
+ let seen = steps(rig);
+ assert_eq!(seen.len(), 2, "{why}: {seen:?}");
+ assert!(matches!(seen[0], Step::Begin { .. }) && matches!(seen[1], Step::Finish { .. }), "{why}: {seen:?}");
+ };
+ // Refused by the blocklist, and with no screenshot yet.
+ let rig_refused = rig();
+ assert!(is_error(&rig_refused.call("click", json!({"x": 1, "y": 1}))));
+ one_each(&rig_refused, "no screenshot");
+ rig_refused.ready();
+ steps(&rig_refused);
+ *rig_refused.desktop.owner_at.lock().unwrap() =
+ Box::new(|_| Some(app(300, "com.apple.systempreferences", "System Settings")));
+ assert!(is_error(&rig_refused.call("click", json!({"x": 10, "y": 10}))));
+ one_each(&rig_refused, "blocked");
+ // Declined by the user.
+ let rig_declined = rig_with(true, false);
+ rig_declined.ready();
+ steps(&rig_declined);
+ *rig_declined.desktop.elements.lock().unwrap() = send_button();
+ assert!(is_error(&rig_declined.call("click", json!({"x": 10, "y": 10}))));
+ one_each(&rig_declined, "declined");
+ // Stopped in the middle of a batch.
+ let rig_stopped = rig();
+ rig_stopped.ready();
+ steps(&rig_stopped);
+ let control = rig_stopped.control.clone();
+ *rig_stopped.clock.on_sleep.lock().unwrap() = Some(Box::new(move || control.end(Reason::Panic)));
+ let steps_json = json!([{"tool": "click", "x": 10, "y": 10}, {"tool": "click", "x": 20, "y": 20}]);
+ assert!(is_error(&rig_stopped.call("batch", batch(steps_json))));
+ one_each(&rig_stopped, "stopped");
+ assert_eq!(rig_stopped.desktop.events().len(), 1);
+ }
+
+ /// Races between preparation, Stop, and late acknowledgements, with the real `Working` coordinator.
+ mod preparation_races {
+ use super::*;
+ use super::super::super::working::{self as w, MainThread, Part, Rings, Task, Visibility, Windows, Working};
+ use std::sync::atomic::{AtomicBool, AtomicU64};
+ use std::time::{Duration, Instant};
+
+ #[derive(Default)]
+ struct Wins { vis: Mutex<Visibility>, log: Mutex<Vec<String>> }
+ impl Windows for Wins {
+ fn is_visible(&self, p: Part) -> bool { self.vis.lock().unwrap().get(p) }
+ fn hide(&self, p: Part) -> Result<(), String> {
+ let mut v = self.vis.lock().unwrap();
+ match p { Part::Dot => v.dot = false, Part::Panel => v.panel = false }
+ self.log.lock().unwrap().push(format!("hide {p:?}")); Ok(())
+ }
+ fn show(&self, p: Part) {
+ let mut v = self.vis.lock().unwrap();
+ match p { Part::Dot => v.dot = true, Part::Panel => v.panel = true }
+ self.log.lock().unwrap().push(format!("show {p:?}"));
+ }
+ fn rose_hidden(&self) -> bool { false }
+ }
+ /// Overlay: acks with `ack_offset` added (None = never acks), after `delay`.
+ struct Ring { w: Mutex<Option<std::sync::Weak<Working>>>, ack: Mutex<Option<i64>>, log: Mutex<Vec<String>>, last: AtomicU64 }
+ impl Rings for Ring {
+ fn show(&self, op: u64) -> Result<(), String> {
+ self.log.lock().unwrap().push(format!("on {op}"));
+ self.last.store(op, Ordering::SeqCst);
+ if let (Some(off), Some(w)) = (*self.ack.lock().unwrap(), self.w.lock().unwrap().as_ref().and_then(|w| w.upgrade())) {
+ w.acknowledge("glow", (op as i64 + off) as u64).ok();
+ }
+ Ok(())
+ }
+ fn end(&self, op: u64) { self.log.lock().unwrap().push(format!("off {op}")); }
+ }
+ /// Main thread: inline, or a real separate thread with a queue.
+ struct Main { deferred: AtomicBool, q: Mutex<Vec<Task>> }
+ impl MainThread for Main {
+ fn run(&self, t: Task) -> Result<(), String> {
+ if self.deferred.load(Ordering::SeqCst) { self.q.lock().unwrap().push(t); } else { t(); }
+ Ok(())
+ }
+ }
+ impl Main { fn drain(&self) { let ts: Vec<Task> = std::mem::take(&mut *self.q.lock().unwrap()); for t in ts { t(); } } }
+
+ struct P { rig: Rig, wins: Arc<Wins>, ring: Arc<Ring>, main: Arc<Main>, working: Arc<Working> }
+ fn probe(allow: bool, confirm: bool, timeout: Duration) -> P {
+ let base = rig_with(allow, confirm);
+ let wins = Arc::new(Wins::default());
+ *wins.vis.lock().unwrap() = Visibility { dot: true, panel: true };
+ let ring = Arc::new(Ring { w: Mutex::new(None), ack: Mutex::new(Some(0)), log: Mutex::new(vec![]), last: AtomicU64::new(0) });
+ let main = Arc::new(Main { deferred: AtomicBool::new(false), q: Mutex::new(vec![]) });
+ let working = Arc::new(Working::new(wins.clone(), ring.clone(), main.clone(), timeout));
+ *ring.w.lock().unwrap() = Some(Arc::downgrade(&working));
+ let helper = Helper::new(base.desktop.clone(), base.dialogs.clone(), base.clock.clone(), base.control.clone(), TOKEN.into(), OWN_PID)
+ .with_working(working.clone());
+ P { rig: Rig { helper, ..base }, wins, ring, main, working }
+ }
+ const BOTH: Visibility = Visibility { dot: true, panel: true };
+
+ #[test]
+ fn a_stop_while_waiting_for_the_rings_posts_nothing_and_restores_the_windows() {
+ let p = probe(true, true, Duration::from_secs(3));
+ p.rig.ready();
+ let caps = p.rig.desktop.captures.load(Ordering::SeqCst);
+ *p.ring.ack.lock().unwrap() = None; // overlay never acks
+ let control = p.rig.control.clone();
+ let t = std::thread::spawn(move || { std::thread::sleep(Duration::from_millis(100)); control.end(Reason::Stopped); });
+ // The real app wires Control's notify to session_ended; emulate that wiring here.
+ let working = p.working.clone();
+ let ring = p.ring.clone();
+ let watcher = std::thread::spawn(move || { std::thread::sleep(Duration::from_millis(150)); working.session_ended(); let _ = ring; });
+ let started = Instant::now();
+ let result = p.rig.call("click", json!({"x": 10, "y": 10}));
+ t.join().unwrap(); watcher.join().unwrap();
+ assert!(is_error(&result));
+ assert_eq!(first_text(&result), STOPPED);
+ assert!(started.elapsed() < Duration::from_secs(1), "{:?}", started.elapsed());
+ assert!(p.rig.desktop.events().is_empty());
+ assert_eq!(p.rig.desktop.captures.load(Ordering::SeqCst), caps);
+ assert_eq!(*p.wins.vis.lock().unwrap(), BOTH);
+ // A late acknowledgement for the stopped operation is ignored.
+ assert_eq!(p.working.acknowledge("glow", 2), Ok(false));
+ assert_eq!(*p.wins.vis.lock().unwrap(), BOTH);
+ }
+
+
+ #[test]
+ fn an_acknowledgement_for_an_older_operation_is_ignored() {
+ let p = probe(true, true, Duration::from_millis(150));
+ p.rig.ready(); // op 1 completes
+ *p.ring.ack.lock().unwrap() = Some(-1); // overlay acks op N-1
+ let result = p.rig.call("click", json!({"x": 10, "y": 10}));
+ assert!(is_error(&result));
+ assert_eq!(first_text(&result), w::UNAVAILABLE);
+ assert!(p.rig.desktop.events().is_empty());
+ assert_eq!(*p.wins.vis.lock().unwrap(), BOTH);
+ assert_eq!(*p.wins.log.lock().unwrap(), ["hide Dot", "hide Panel", "show Dot", "show Panel"]);
+ // Only the glow window may acknowledge.
+ assert!(p.working.acknowledge("panel", 3).is_err());
+ assert!(p.working.acknowledge("dot", 3).is_err());
+ }
+
+
+ #[test]
+ fn a_hide_that_runs_after_its_timeout_hides_nothing() {
+ let p = probe(true, true, Duration::from_millis(120));
+ p.rig.ready();
+ p.main.deferred.store(true, Ordering::SeqCst);
+ let result = p.rig.call("key", json!({"combo": "tab"}));
+ assert!(is_error(&result));
+ assert_eq!(first_text(&result), w::NOT_HIDDEN);
+ assert!(p.rig.desktop.events().is_empty());
+ p.main.drain();
+ assert_eq!(*p.wins.vis.lock().unwrap(), BOTH);
+ assert_eq!(p.wins.log.lock().unwrap().len(), 4, "{:?}", p.wins.log.lock().unwrap());
+ }
+
+
+ #[test]
+ fn a_concurrent_stop_always_restores_the_windows_and_never_acts_after_failing() {
+ // A separate "main" thread drains the queue; Stop arrives concurrently. Repeat to shake races.
+ for i in 0..50u64 {
+ let p = probe(true, true, Duration::from_millis(500));
+ p.rig.ready();
+ p.main.deferred.store(true, Ordering::SeqCst);
+ let stop = Arc::new(AtomicBool::new(false));
+ let (m, s) = (p.main.clone(), stop.clone());
+ let mainthr = std::thread::spawn(move || { while !s.load(Ordering::SeqCst) { m.drain(); std::thread::yield_now(); } m.drain(); });
+ let (c, wk) = (p.rig.control.clone(), p.working.clone());
+ let stopper = std::thread::spawn(move || {
+ std::thread::sleep(Duration::from_micros(i * 5));
+ c.end(Reason::Stopped);
+ wk.session_ended();
+ });
+ let r = p.rig.call("click", json!({"x": 10, "y": 10}));
+ stopper.join().unwrap();
+ std::thread::sleep(Duration::from_millis(2));
+ stop.store(true, Ordering::SeqCst);
+ mainthr.join().unwrap();
+ assert_eq!(*p.wins.vis.lock().unwrap(), BOTH, "iter {i}: {:?} {r}", p.wins.log.lock().unwrap());
+ assert!(p.rig.desktop.events().len() <= 1);
+ if is_error(&r) { assert!(p.rig.desktop.events().is_empty(), "iter {i}"); }
+ assert!(!p.working.is_current(p.ring.last.load(Ordering::SeqCst)));
+ }
+ }
+
+
+ }
}
diff --git a/apps/desktop/src-tauri/src/computer/mod.rs b/apps/desktop/src-tauri/src/computer/mod.rs
index 5e619b5..32c2783 100644
--- a/apps/desktop/src-tauri/src/computer/mod.rs
+++ b/apps/desktop/src-tauri/src/computer/mod.rs
@@ -22,6 +22,7 @@ pub mod risk;
pub mod server;
pub mod session;
pub mod windows;
+pub mod working;
use blocklist::AppIdentity;
use coords::{Point, ScreenshotGeometry};
diff --git a/apps/desktop/src-tauri/src/computer/working.rs b/apps/desktop/src-tauri/src/computer/working.rs
new file mode 100644
index 0000000..fd1e21f
--- /dev/null
+++ b/apps/desktop/src-tauri/src/computer/working.rs
@@ -0,0 +1,646 @@
+//! The working rings (S1, S2, S5): while a screenshot or an action runs, Gentle Dot hides the
+//! Dot and the panel and shows pink rings at the top of the controlled display instead.
+//!
+//! An operation starts only from a confirmed state: the overlay is ordered in and told to draw
+//! (`computer://working`), the overlay acknowledges the rings it drew (`computer_working_ready`),
+//! then the Dot and the panel are hidden on the main thread. Every wait is bounded. Finishing an
+//! operation, or the end of the session (Stop, panic, timeout), clears the rings and shows again
+//! exactly what the operation hid, without focusing it; an operation that ended is fenced out,
+//! so a late acknowledgement or a queued hide does nothing. Nothing guarantees restoring after
+//! the process aborts or while the main thread is blocked.
+
+use serde::Serialize;
+use std::sync::{Arc, Condvar, Mutex, MutexGuard};
+use std::time::{Duration, Instant};
+
+/// Sent to the overlay only: draw the rings for `operationId`, or stop drawing them.
+pub const WORKING_EVENT: &str = "computer://working";
+/// How long the overlay has to acknowledge the rings, and the main thread to hide the windows.
+pub const READY_TIMEOUT: Duration = Duration::from_secs(2);
+pub const UNAVAILABLE: &str =
+ "Gentle Dot could not show that it is working, so nothing was done. Try again.";
+pub const NOT_HIDDEN: &str = "Gentle Dot could not move its own windows out of the way, so nothing was done. Try again.";
+
+/// The `computer://working` payload.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct WorkingEvent {
+ pub active: bool,
+ pub operation_id: u64,
+}
+
+/// One of the windows an operation hides.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum Part {
+ Dot,
+ Panel,
+}
+
+const PARTS: [Part; 2] = [Part::Dot, Part::Panel];
+
+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
+pub struct Visibility {
+ pub dot: bool,
+ pub panel: bool,
+}
+
+impl Visibility {
+ pub fn get(&self, part: Part) -> bool {
+ match part {
+ Part::Dot => self.dot,
+ Part::Panel => self.panel,
+ }
+ }
+
+ fn set(&mut self, part: Part, on: bool) {
+ match part {
+ Part::Dot => self.dot = on,
+ Part::Panel => self.panel = on,
+ }
+ }
+}
+
+/// What to show again once an operation ends: what it hid and is still hidden, except a Dot
+/// the user hid meanwhile ("Hide the rose"). A window the user opened again stays as it is.
+pub fn to_restore(hidden: Visibility, now: Visibility, rose_hidden: bool) -> Visibility {
+ Visibility { dot: hidden.dot && !now.dot && !rose_hidden, panel: hidden.panel && !now.panel }
+}
+
+/// The Dot and the panel. Main thread only.
+pub trait Windows: Send + Sync {
+ fn is_visible(&self, part: Part) -> bool;
+ fn hide(&self, part: Part) -> Result<(), String>;
+ /// Orders the window in without focusing it or activating the app.
+ fn show(&self, part: Part);
+ /// The user's "Hide the rose" choice, as it is now.
+ fn rose_hidden(&self) -> bool;
+}
+
+/// The overlay's rings.
+pub trait Rings: Send + Sync {
+ /// Orders the overlay in over the controlled display, then tells it to draw the rings for
+ /// `operation`. Returns once both happened, or why not; never waits unbounded.
+ fn show(&self, operation: u64) -> Result<(), String>;
+ /// Tells the overlay to stop drawing the rings for `operation`; never waits.
+ fn end(&self, operation: u64);
+}
+
+pub type Task = Box<dyn FnOnce() + Send>;
+
+pub trait MainThread: Send + Sync {
+ /// Runs `task` on the main thread: queued in order, or at once when called there.
+ fn run(&self, task: Task) -> Result<(), String>;
+}
+
+/// What the MCP helper needs around each call that captures or acts (S1, S5).
+pub trait Preparation: Send + Sync {
+ /// Returns once the rings show and the Dot and panel are out of the way, or why not (then
+ /// nothing stays hidden). The operation must be passed to `finish`.
+ fn begin(&self) -> Result<u64, String>;
+ /// Clears the rings and shows again what `operation` hid; does nothing once it ended.
+ fn finish(&self, operation: u64);
+}
+
+/// No rings and nothing hidden: the helper without an overlay, as in most tests.
+pub struct NoPreparation;
+
+impl Preparation for NoPreparation {
+ fn begin(&self) -> Result<u64, String> {
+ Ok(0)
+ }
+
+ fn finish(&self, _operation: u64) {}
+}
+
+#[derive(Default)]
+struct State {
+ last: u64,
+ current: Option<Op>,
+ /// What operations hid that has not been shown again yet.
+ hidden: Visibility,
+}
+
+struct Op {
+ id: u64,
+ /// The overlay acknowledged the rings.
+ ready: bool,
+ /// The main thread hid the windows, or why it could not.
+ hid: Option<Result<(), String>>,
+}
+
+/// Why a wait in `begin` gave up.
+enum Gave {
+ Ended,
+ TimedOut,
+}
+
+struct Inner {
+ windows: Arc<dyn Windows>,
+ rings: Arc<dyn Rings>,
+ main: Arc<dyn MainThread>,
+ timeout: Duration,
+ state: Mutex<State>,
+ changed: Condvar,
+}
+
+pub struct Working(Arc<Inner>);
+
+impl Working {
+ pub fn new(windows: Arc<dyn Windows>, rings: Arc<dyn Rings>, main: Arc<dyn MainThread>, timeout: Duration) -> Self {
+ Working(Arc::new(Inner {
+ windows,
+ rings,
+ main,
+ timeout,
+ state: Mutex::new(State::default()),
+ changed: Condvar::new(),
+ }))
+ }
+
+ /// Whether `operation` is the one running now (the overlay drops a late start).
+ pub fn is_current(&self, operation: u64) -> bool {
+ self.0.lock().current.as_ref().is_some_and(|op| op.id == operation)
+ }
+
+ /// The overlay drew the rings for `operation`. False when it is not the one running now.
+ pub fn ready(&self, operation: u64) -> bool {
+ let mut state = self.0.lock();
+ let Some(op) = state.current.as_mut().filter(|op| op.id == operation) else {
+ return false;
+ };
+ op.ready = true;
+ self.0.changed.notify_all();
+ true
+ }
+
+ /// `computer_working_ready` from the window labeled `window`: only the overlay may say so.
+ pub fn acknowledge(&self, window: &str, operation: u64) -> Result<bool, String> {
+ if window != super::app::GLOW_WINDOW {
+ return Err("Only the computer-control overlay reports the working rings.".into());
+ }
+ Ok(self.ready(operation))
+ }
+
+ /// The session ended (Stop, panic, timeout): the running operation ends at once.
+ pub fn session_ended(&self) {
+ let running = self.0.lock().current.as_ref().map(|op| op.id);
+ if let Some(operation) = running {
+ self.finish(operation);
+ }
+ }
+
+ /// Waits until `done` holds for `operation`, it ended, or the time is up.
+ fn wait(&self, operation: u64, done: impl Fn(&Op) -> bool) -> Result<(), Gave> {
+ let deadline = Instant::now() + self.0.timeout;
+ let mut state = self.0.lock();
+ loop {
+ match state.current.as_ref().filter(|op| op.id == operation) {
+ None => return Err(Gave::Ended),
+ Some(op) if done(op) => return Ok(()),
+ Some(_) => {}
+ }
+ let left = deadline.saturating_duration_since(Instant::now());
+ if left.is_zero() {
+ return Err(Gave::TimedOut);
+ }
+ state = self.0.changed.wait_timeout(state, left).unwrap_or_else(|p| p.into_inner()).0;
+ }
+ }
+
+ /// Ends `operation` after a failed step of `begin`, with `error`.
+ fn abandon(&self, operation: u64, error: &str) -> String {
+ self.finish(operation);
+ error.to_string()
+ }
+}
+
+impl Inner {
+ fn lock(&self) -> MutexGuard<'_, State> {
+ self.state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
+ }
+
+ /// On the main thread: hides the visible windows for `operation`, unless it already ended.
+ fn hide(&self, operation: u64) {
+ let mut state = self.lock();
+ if !state.current.as_ref().is_some_and(|op| op.id == operation) {
+ return;
+ }
+ let mut outcome = Ok(());
+ for part in PARTS {
+ if !self.windows.is_visible(part) {
+ continue;
+ }
+ if let Err(error) = self.windows.hide(part) {
+ outcome = Err(error);
+ break;
+ }
+ state.hidden.set(part, true);
+ }
+ if let Some(op) = state.current.as_mut() {
+ op.hid = Some(outcome);
+ }
+ self.changed.notify_all();
+ }
+
+ /// On the main thread: shows again what operations hid, as the user left things meanwhile.
+ fn restore(&self) {
+ let hidden = std::mem::take(&mut self.lock().hidden);
+ let now = Visibility { dot: self.windows.is_visible(Part::Dot), panel: self.windows.is_visible(Part::Panel) };
+ let show = to_restore(hidden, now, self.windows.rose_hidden());
+ for part in PARTS.into_iter().filter(|part| show.get(*part)) {
+ self.windows.show(part);
+ }
+ }
+}
+
+impl Preparation for Working {
+ fn begin(&self) -> Result<u64, String> {
+ // Calls are serialized; one still running here was left behind, and ends now.
+ self.session_ended();
+ let operation = {
+ let mut state = self.0.lock();
+ state.last += 1;
+ state.current = Some(Op { id: state.last, ready: false, hid: None });
+ state.last
+ };
+ if let Err(error) = self.0.rings.show(operation) {
+ eprintln!("gentle-dot: cannot show the working rings: {error}");
+ return Err(self.abandon(operation, UNAVAILABLE));
+ }
+ if self.wait(operation, |op| op.ready).is_err() {
+ return Err(self.abandon(operation, UNAVAILABLE));
+ }
+ let inner = self.0.clone();
+ if let Err(error) = self.0.main.run(Box::new(move || inner.hide(operation))) {
+ eprintln!("gentle-dot: cannot hide the Dot and the panel: {error}");
+ return Err(self.abandon(operation, NOT_HIDDEN));
+ }
+ if let Err(gave) = self.wait(operation, |op| op.hid.is_some()) {
+ let error = match gave {
+ Gave::Ended => UNAVAILABLE,
+ Gave::TimedOut => NOT_HIDDEN,
+ };
+ return Err(self.abandon(operation, error));
+ }
+ let hid = self.0.lock().current.as_ref().filter(|op| op.id == operation).and_then(|op| op.hid.clone());
+ match hid {
+ Some(Ok(())) => Ok(operation),
+ Some(Err(error)) => {
+ eprintln!("gentle-dot: cannot hide the Dot and the panel: {error}");
+ Err(self.abandon(operation, NOT_HIDDEN))
+ }
+ None => Err(self.abandon(operation, UNAVAILABLE)),
+ }
+ }
+
+ fn finish(&self, operation: u64) {
+ {
+ let mut state = self.0.lock();
+ if !state.current.as_ref().is_some_and(|op| op.id == operation) {
+ return;
+ }
+ state.current = None;
+ }
+ // No lock held from here: on the main thread, `run` runs the task at once.
+ self.0.changed.notify_all();
+ self.0.rings.end(operation);
+ let inner = self.0.clone();
+ if let Err(error) = self.0.main.run(Box::new(move || inner.restore())) {
+ eprintln!("gentle-dot: cannot show the Dot and the panel again: {error}");
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::atomic::{AtomicBool, Ordering};
+ use std::sync::Weak;
+ use std::time::Instant;
+
+ type Log = Arc<Mutex<Vec<String>>>;
+ type Hook = Box<dyn Fn(u64) + Send + Sync>;
+
+ const SHORT: Duration = Duration::from_millis(100);
+
+ struct FakeWindows {
+ log: Log,
+ visible: Mutex<Visibility>,
+ rose_hidden: AtomicBool,
+ fails: Mutex<Option<Part>>,
+ }
+
+ fn name(part: Part) -> &'static str {
+ match part {
+ Part::Dot => "dot",
+ Part::Panel => "panel",
+ }
+ }
+
+ impl Windows for FakeWindows {
+ fn is_visible(&self, part: Part) -> bool {
+ self.visible.lock().unwrap().get(part)
+ }
+
+ fn hide(&self, part: Part) -> Result<(), String> {
+ if *self.fails.lock().unwrap() == Some(part) {
+ return Err(format!("cannot hide the {}", name(part)));
+ }
+ self.visible.lock().unwrap().set(part, false);
+ self.log.lock().unwrap().push(format!("hide {}", name(part)));
+ Ok(())
+ }
+
+ fn show(&self, part: Part) {
+ self.visible.lock().unwrap().set(part, true);
+ self.log.lock().unwrap().push(format!("show {}", name(part)));
+ }
+
+ fn rose_hidden(&self) -> bool {
+ self.rose_hidden.load(Ordering::SeqCst)
+ }
+ }
+
+ struct FakeRings {
+ log: Log,
+ fails: AtomicBool,
+ /// What the overlay does once told to draw (by default, acknowledge it).
+ on_show: Mutex<Option<Hook>>,
+ }
+
+ impl Rings for FakeRings {
+ fn show(&self, operation: u64) -> Result<(), String> {
+ if self.fails.load(Ordering::SeqCst) {
+ return Err("the overlay is unavailable".into());
+ }
+ self.log.lock().unwrap().push(format!("rings on {operation}"));
+ if let Some(hook) = self.on_show.lock().unwrap().as_ref() {
+ hook(operation);
+ }
+ Ok(())
+ }
+
+ fn end(&self, operation: u64) {
+ self.log.lock().unwrap().push(format!("rings off {operation}"));
+ }
+ }
+
+ /// Runs tasks at once, or queues them until `drain` when `deferred` (then `after_queue` runs
+ /// once, after the first task is queued).
+ struct FakeMain {
+ deferred: AtomicBool,
+ queue: Mutex<Vec<Task>>,
+ after_queue: Mutex<Option<Box<dyn Fn() + Send + Sync>>>,
+ }
+
+ impl MainThread for FakeMain {
+ fn run(&self, task: Task) -> Result<(), String> {
+ if !self.deferred.load(Ordering::SeqCst) {
+ task();
+ return Ok(());
+ }
+ self.queue.lock().unwrap().push(task);
+ let hook = self.after_queue.lock().unwrap().take();
+ if let Some(hook) = hook {
+ hook();
+ }
+ Ok(())
+ }
+ }
+
+ impl FakeMain {
+ fn drain(&self) {
+ let tasks: Vec<Task> = std::mem::take(&mut *self.queue.lock().unwrap());
+ for task in tasks {
+ task();
+ }
+ }
+ }
+
+ struct Rig {
+ working: Arc<Working>,
+ windows: Arc<FakeWindows>,
+ rings: Arc<FakeRings>,
+ main: Arc<FakeMain>,
+ log: Log,
+ }
+
+ fn rig_with(visible: Visibility, timeout: Duration) -> Rig {
+ let log: Log = Arc::default();
+ let windows = Arc::new(FakeWindows {
+ log: log.clone(),
+ visible: Mutex::new(visible),
+ rose_hidden: AtomicBool::new(!visible.dot),
+ fails: Mutex::new(None),
+ });
+ let rings = Arc::new(FakeRings { log: log.clone(), fails: AtomicBool::new(false), on_show: Mutex::new(None) });
+ let main =
+ Arc::new(FakeMain { deferred: AtomicBool::new(false), queue: Mutex::new(Vec::new()), after_queue: Mutex::new(None) });
+ let working = Arc::new(Working::new(windows.clone(), rings.clone(), main.clone(), timeout));
+ let rig = Rig { working, windows, rings, main, log };
+ rig.on_show(|working, operation| {
+ working.ready(operation);
+ });
+ rig
+ }
+
+ fn rig() -> Rig {
+ rig_with(Visibility { dot: true, panel: true }, SHORT)
+ }
+
+ impl Rig {
+ /// What the overlay does once told to draw the rings.
+ fn on_show(&self, hook: impl Fn(&Working, u64) + Send + Sync + 'static) {
+ let working: Weak<Working> = Arc::downgrade(&self.working);
+ *self.rings.on_show.lock().unwrap() = Some(Box::new(move |operation| {
+ if let Some(working) = working.upgrade() {
+ hook(&working, operation);
+ }
+ }));
+ }
+
+ fn log(&self) -> Vec<String> {
+ self.log.lock().unwrap().clone()
+ }
+
+ fn visible(&self) -> Visibility {
+ *self.windows.visible.lock().unwrap()
+ }
+ }
+
+ const BOTH: Visibility = Visibility { dot: true, panel: true };
+
+ #[test]
+ fn an_operation_shows_the_rings_hides_the_windows_and_puts_them_back() {
+ let rig = rig();
+ let operation = rig.working.begin().unwrap();
+ assert_eq!(rig.log(), ["rings on 1", "hide dot", "hide panel"]);
+ assert_eq!(rig.visible(), Visibility::default());
+ rig.working.finish(operation);
+ assert_eq!(rig.log(), ["rings on 1", "hide dot", "hide panel", "rings off 1", "show dot", "show panel"]);
+ assert_eq!(rig.visible(), BOTH);
+ }
+
+ #[test]
+ fn only_what_was_visible_is_hidden_and_shown_again() {
+ // The user hid the rose and the panel is open.
+ let rig = rig_with(Visibility { dot: false, panel: true }, SHORT);
+ let operation = rig.working.begin().unwrap();
+ rig.working.finish(operation);
+ assert_eq!(rig.log(), ["rings on 1", "hide panel", "rings off 1", "show panel"]);
+ // Nothing open: nothing hidden, nothing shown, the rings still come and go.
+ let rig = rig_with(Visibility::default(), SHORT);
+ let operation = rig.working.begin().unwrap();
+ rig.working.finish(operation);
+ assert_eq!(rig.log(), ["rings on 1", "rings off 1"]);
+ }
+
+ #[test]
+ fn restoring_keeps_what_the_user_changed_meanwhile() {
+ let hidden = BOTH;
+ // "Hide the rose" during the call keeps the Dot hidden; a reopened panel is left alone.
+ assert_eq!(to_restore(hidden, Visibility::default(), true), Visibility { dot: false, panel: true });
+ assert_eq!(to_restore(hidden, Visibility { dot: false, panel: true }, false), Visibility { dot: true, panel: false });
+ assert_eq!(to_restore(hidden, Visibility::default(), false), BOTH);
+ // What the operation did not hide is never shown.
+ assert_eq!(to_restore(Visibility::default(), Visibility::default(), false), Visibility::default());
+
+ let rig = rig();
+ let operation = rig.working.begin().unwrap();
+ rig.windows.rose_hidden.store(true, Ordering::SeqCst);
+ rig.windows.visible.lock().unwrap().panel = true;
+ rig.working.finish(operation);
+ assert_eq!(rig.log(), ["rings on 1", "hide dot", "hide panel", "rings off 1"]);
+ assert_eq!(rig.visible(), Visibility { dot: false, panel: true });
+ }
+
+ #[test]
+ fn without_an_acknowledgement_nothing_is_hidden_and_the_wait_is_bounded() {
+ let rig = rig();
+ rig.on_show(|_, _| {});
+ let started = Instant::now();
+ assert_eq!(rig.working.begin(), Err(UNAVAILABLE.to_string()));
+ let waited = started.elapsed();
+ assert!(waited >= SHORT && waited < Duration::from_secs(2), "{waited:?}");
+ assert_eq!(rig.log(), ["rings on 1", "rings off 1"]);
+ assert_eq!(rig.visible(), BOTH);
+ // A late acknowledgement revives nothing.
+ assert!(!rig.working.ready(1));
+ assert_eq!(rig.log(), ["rings on 1", "rings off 1"]);
+ }
+
+ #[test]
+ fn an_acknowledgement_must_name_the_running_operation() {
+ let rig = rig();
+ assert!(!rig.working.ready(1), "nothing runs yet");
+ rig.on_show(|working, operation| {
+ working.ready(operation + 1);
+ working.ready(operation - 1);
+ });
+ assert_eq!(rig.working.begin(), Err(UNAVAILABLE.to_string()));
+ assert_eq!(rig.visible(), BOTH);
+ assert!(!rig.working.is_current(1));
+ }
+
+ #[test]
+ fn only_the_glow_window_acknowledges() {
+ let rig = rig();
+ let answers: Arc<Mutex<Vec<Result<bool, String>>>> = Arc::default();
+ let seen = answers.clone();
+ rig.on_show(move |working, operation| {
+ let mut seen = seen.lock().unwrap();
+ seen.push(working.acknowledge("panel", operation));
+ seen.push(working.acknowledge("dot", operation));
+ seen.push(working.acknowledge("glow", operation + 7));
+ seen.push(working.acknowledge("glow", operation));
+ });
+ let operation = rig.working.begin().unwrap();
+ let answers = answers.lock().unwrap().clone();
+ assert!(answers[0].is_err() && answers[1].is_err(), "{answers:?}");
+ assert_eq!(answers[2..], [Ok(false), Ok(true)]);
+ rig.working.finish(operation);
+ assert_eq!(rig.working.acknowledge("glow", operation), Ok(false));
+ }
+
+ #[test]
+ fn a_rings_failure_hides_nothing_and_does_not_wait() {
+ let rig = rig_with(BOTH, Duration::from_secs(5));
+ rig.rings.fails.store(true, Ordering::SeqCst);
+ let started = Instant::now();
+ assert_eq!(rig.working.begin(), Err(UNAVAILABLE.to_string()));
+ assert!(started.elapsed() < Duration::from_secs(1));
+ assert!(rig.log().iter().all(|line| !line.starts_with("hide")), "{:?}", rig.log());
+ assert_eq!(rig.visible(), BOTH);
+ assert!(!rig.working.is_current(1));
+ }
+
+ #[test]
+ fn a_hide_failure_puts_back_what_was_hidden_and_fails() {
+ let rig = rig();
+ *rig.windows.fails.lock().unwrap() = Some(Part::Panel);
+ assert_eq!(rig.working.begin(), Err(NOT_HIDDEN.to_string()));
+ assert_eq!(rig.log(), ["rings on 1", "hide dot", "rings off 1", "show dot"]);
+ assert_eq!(rig.visible(), BOTH);
+ }
+
+ #[test]
+ fn a_session_end_while_waiting_for_the_rings_fails_at_once() {
+ let rig = rig_with(BOTH, Duration::from_secs(5));
+ rig.on_show(|working, _| working.session_ended());
+ let started = Instant::now();
+ assert!(rig.working.begin().is_err());
+ assert!(started.elapsed() < Duration::from_secs(1));
+ assert_eq!(rig.log(), ["rings on 1", "rings off 1"]);
+ assert_eq!(rig.visible(), BOTH);
+ }
+
+ #[test]
+ fn a_stop_before_the_queued_hide_runs_hides_nothing() {
+ let rig = rig_with(BOTH, Duration::from_secs(5));
+ rig.main.deferred.store(true, Ordering::SeqCst);
+ let working = Arc::downgrade(&rig.working);
+ *rig.main.after_queue.lock().unwrap() = Some(Box::new(move || {
+ if let Some(working) = working.upgrade() {
+ working.session_ended();
+ }
+ }));
+ assert!(rig.working.begin().is_err());
+ rig.main.drain();
+ assert_eq!(rig.log(), ["rings on 1", "rings off 1"]);
+ assert_eq!(rig.visible(), BOTH);
+ }
+
+ #[test]
+ fn a_session_end_during_an_operation_puts_everything_back_at_once() {
+ let rig = rig();
+ let operation = rig.working.begin().unwrap();
+ rig.working.session_ended();
+ assert_eq!(rig.visible(), BOTH);
+ assert!(!rig.working.is_current(operation));
+ // The call's own finish comes later and does nothing more.
+ rig.working.finish(operation);
+ assert_eq!(rig.log(), ["rings on 1", "hide dot", "hide panel", "rings off 1", "show dot", "show panel"]);
+ }
+
+ #[test]
+ fn a_late_finish_leaves_a_newer_operation_alone() {
+ let rig = rig();
+ let first = rig.working.begin().unwrap();
+ rig.working.finish(first);
+ let second = rig.working.begin().unwrap();
+ assert_eq!(second, first + 1);
+ rig.working.finish(first);
+ assert!(rig.working.is_current(second));
+ assert_eq!(rig.visible(), Visibility::default());
+ rig.working.finish(second);
+ assert_eq!(rig.visible(), BOTH);
+ assert_eq!(rig.log().iter().filter(|line| line.starts_with("rings off")).count(), 2);
+ }
+
+ #[test]
+ fn the_working_event_names_its_operation() {
+ let event = WorkingEvent { active: true, operation_id: 3 };
+ assert_eq!(serde_json::to_value(event).unwrap(), serde_json::json!({"active": true, "operationId": 3}));
+ assert_eq!(WORKING_EVENT, "computer://working");
+ }
+}
diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rs
index d868975..ac7cd0b 100644
--- a/apps/desktop/src-tauri/src/shell.rs
+++ b/apps/desktop/src-tauri/src/shell.rs
@@ -7,6 +7,7 @@ use crate::approvals::{native::NativePrompt, ApprovalRequest, Approvals, Decisio
use crate::computer::app as computer;
use crate::computer::server::Endpoint;
use crate::computer::session::Reason;
+use crate::computer::working::{self, Part};
use crate::config::{self, ConnectionInfo, DesktopConfig, DEFAULT_SHORTCUT};
use crate::daemon::{self, Daemon, RestartOutcome};
use crate::geometry::{self, Rect};
@@ -68,6 +69,45 @@ struct Shell {
shortcut: Mutex<Option<String>>,
}
+/// The Dot and the panel as computer control hides them during a call (S1, S5): never through
+/// `hide_panel` or `show_panel`, so the remembered spot, the full-screen frame, the rose choice,
+/// and the keyboard focus stay as they were. Main thread only.
+struct ShellWindows(AppHandle);
+
+impl ShellWindows {
+ fn get(&self, part: Part) -> Option<WebviewWindow> {
+ self.0.get_webview_window(match part {
+ Part::Dot => DOT,
+ Part::Panel => PANEL,
+ })
+ }
+}
+
+impl working::Windows for ShellWindows {
+ fn is_visible(&self, part: Part) -> bool {
+ self.get(part).and_then(|window| window.is_visible().ok()).unwrap_or(false)
+ }
+
+ fn hide(&self, part: Part) -> Result<(), String> {
+ self.get(part).ok_or_else(|| format!("window {part:?} is missing"))?.hide().map_err(err)
+ }
+
+ fn show(&self, part: Part) {
+ let Some(window) = self.get(part) else { return };
+ #[cfg(target_os = "macos")]
+ let shown = computer::show_without_focus(&window);
+ #[cfg(not(target_os = "macos"))]
+ let shown = window.show().map_err(err);
+ if let Err(error) = shown {
+ eprintln!("gentle-dot: cannot show the {part:?} again: {error}");
+ }
+ }
+
+ fn rose_hidden(&self) -> bool {
+ self.0.try_state::<Shell>().is_some_and(|shell| shell.rose_hidden.load(Ordering::SeqCst))
+ }
+}
+
/// The tray's rose item, relabeled when the rose is hidden or shown.
struct RoseMenuItem(MenuItem<tauri::Wry>);
@@ -766,6 +806,7 @@ pub fn run() {
computer::computer_stop,
computer::computer_status,
computer::computer_set_yolo,
+ computer::computer_working_ready,
voice::voice_status,
voice::voice_start,
voice::voice_stop,
@@ -781,7 +822,7 @@ pub fn run() {
let handle = app.handle().clone();
// Computer control first: a daemon this app spawns gets the helper over its channel.
- let computer = computer::start(&handle);
+ let computer = computer::start(&handle, Arc::new(ShellWindows(handle.clone())));
let service = ChannelService {
approvals: Approvals::new(Arc::new(NativePrompt::new(handle.clone())), APPROVAL_TIMEOUT),
computer: computer.endpoint(),
@@ -926,6 +967,22 @@ mod tests {
}
}
+ #[test]
+ fn only_the_glow_overlay_may_acknowledge_the_working_rings() {
+ let build = include_str!("../build.rs");
+ assert!(build.contains("\"computer_working_ready\","), "computer_working_ready is missing from build.rs");
+ let capabilities: serde_json::Value =
+ serde_json::from_str(include_str!("../capabilities/default.json")).unwrap();
+ let windows: Vec<&serde_json::Value> = capabilities["capabilities"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|c| c["permissions"].as_array().unwrap().iter().any(|p| p == "allow-computer-working-ready"))
+ .flat_map(|c| c["windows"].as_array().unwrap())
+ .collect();
+ assert_eq!(windows, [computer::GLOW_WINDOW]);
+ }
+
#[test]
fn the_windows_listen_for_the_assistant_ready_event() {
let desktop = include_str!("../../../../packages/ui/src/desktop.ts");
diff --git a/docs/design.md b/docs/design.md
index d459bce..f56090a 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -174,7 +174,7 @@ The assistant can see the screen and operate apps through a built-in MCP server
- S24.3 Session grant: the first call without a session shows a native dialog ("Allow Gentle Dot to see and control this Mac for 30 minutes?"). A session ends on timeout, Stop, the tray item, or the panic shortcut ⌥⇧Esc, and queued actions are dropped.
- S24.4 Guards: a fixed blocklist (Gentle Dot itself, System Settings, SecurityAgent, loginwindow, Keychain Access, password managers), 10 actions per second, and a native per-action confirmation for risky actions (send, pay, buy, delete, submit, confirm, transfer, and their Spanish equivalents, by Accessibility role and title, by `return` on a default button, or by the declared `intent`).
- S24.5 Permissions: the app reports and requests Accessibility and Screen Recording (`computer_permissions`, `computer_request_permission {kind}`). The Connectors screen shows a built-in "Computer" entry with both statuses, Grant buttons, Check again, the note that debug builds lose the grants on every rebuild (macOS ties them to the code signature), and a note when the current model does not accept images (`ConnectorInfo.noImages`, from the model's `input` in the engine's `get_state` and `set_model` answers).
-- S24.6 Visible state: the app emits `computer://state {active, endsAt?, reason?}` (`computer_status` gives the current one). While active, the rose shows the "in control" state (`dot-in_control`, mood `control`: accent rim, steady traveling light) and the panel shows "Controlling your Mac · mm:ss left" with Stop (`computer_stop`).
+- S24.6 Visible state: the app emits `computer://state {active, endsAt?, reason?}` (`computer_status` gives the current one). Between calls, the rose shows the "in control" state (`dot-in_control`, mood `control`: accent rim, steady traveling light) and the panel shows "Controlling your Mac · mm:ss left" with Stop (`computer_stop`). During a screenshot or action call (including an entire batch and its final screenshot), the Dot and panel are temporarily hidden and the top edge of the controlled display glows in the rose's neon with a light traveling along it, without text or logo. The click-through glow must be ready and hiding confirmed before capture or input; failed preparation sends no input. Completion and normal error/Stop paths restore prior visibility without changing saved preferences or taking focus. The tray's "Stop computer control" and the panic shortcut remain independent of the hidden panel; shortcut registration and full-screen tray availability must be verified on the target Mac.
- S24.7 Wiring: the app registers its helper itself, over the app channel, right after it spawns the daemon (`computer_register {url, token}`; the daemon accepts only `http://127.0.0.1:<port>/mcp` and a header-safe key). A window cannot register, repoint, or remove it (L61 closed): the panel only calls `computer_endpoint` to know whether a helper exists. The daemon keeps the endpoint in memory, never in `connectors.json`, and renders `computer: {url, headers: {Authorization: "Bearer <key>"}, exposure: "direct"}` into `mcp.json`, then restarts the engine when idle. The guard's policy lists it under `builtin`, so its tools run without in-engine approval cards. It is removed on `computer_unregister` from the app or when the app's channel closes; windows coming and going do not touch it. A daemon without a channel (`pnpm dev`) gets no helper; the app never uses one (§9, Daemon lifecycle). The key is never logged or sent to a window: `connectors` lists only a built-in "Computer" entry (`builtin: true`) that the connector messages cannot change or remove, no saved or imported connector can take the name `computer`, and the import scan never offers the helper.
- S24.8 Speed: `batch {steps: [{tool, ...args}], intent?}` runs 1 to 20 steps of `click`, `move`, `drag`, `scroll`, `type`, `key`, `open_app`, or `wait` in one call and returns one screenshot. Each step takes the single tool's path (session and epoch, blocklist, risky confirmation, N1/N2 typing rules, coordinates mapped with the screenshot taken before the batch) and counts as one action for the rate limit; a full window delays the step instead of refusing it. Steps are 100 ms apart (1.5 s after `open_app`) so each step's guards read the screen the previous one left. The batch's `intent` applies to every step on top of the step's own. The first refused, declined, or failed step stops the batch; the error says which steps ran and comes with a fresh screenshot while the session lasts (none after Stop or panic). Malformed batches (empty, over 20, a nested `batch`, `screenshot`, `list_apps`, unknown tools, invalid arguments) run nothing. Actions settle 150 ms before their screenshot (`open_app` 1.5 s); screenshots are JPEG quality 65; debug builds optimize `image`, `zune-*`, and this crate (opt-level 1, because the generic encoder is compiled here).
- S24.9 Yolo mode: in memory only, off at launch. `computer_set_yolo {enabled}` and the tray item "Yolo mode" switch it; turning it on asks a native confirmation ("Turn on yolo mode? Gentle Dot will send, pay, delete, and submit without asking you first, for up to 1 hour. Stop and ⌥⇧Esc still work.", Turn On / Cancel). While on, only the risky-action confirmation is skipped; the grant, blocklist, rate limit, Stop, and panic are unchanged, and Stop or panic end the session, not yolo mode. It turns itself off after 1 hour. `computer://state` and `computer_status` add `yolo` and `yoloEndsAt?`; every switch reports the resulting state, so a declined confirmation flips the UI switch back. Connectors → Computer shows a "Yolo mode" switch, the banner shows "Yolo", and the rose carries a yellow mark (`dot-yolo`).
@@ -182,6 +182,7 @@ The assistant can see the screen and operate apps through a built-in MCP server
- What it shows: a pulse on a click, a trail along a drag (drawn on the display where the drag starts), short markers for moves and scrolls, and an outline around the focused element after `type` and `key`, when that element reports a frame (`AXPosition`, `AXSize`, read right after the keys); without one, nothing shows. The glow uses the accent `#f095c8`. It fades about 1.5 s after the last action (1.2 s lit, then a 300 ms fade) and clears at once when the session ends (Stop, panic, timeout). With "Reduce motion" it stays still: no pulse and no trail, only the drag's end.
- Where the marks come from: once an action's input is posted, `perform` hands a `Mark` (global points and a kind) to the helper's glow sink. Each batch step that runs gets its own mark. A refused, declined, stopped, or failed action or step reports nothing. `open_app`, `wait`, `screenshot`, and `list_apps` report nothing either. The sink only queues the mark on a channel, so no check, order, timing, or result changes; a rig test runs the same calls with and without the sink and compares them.
- The overlay: a Tauri window `glow` (`index.html?surface=glow`, title `Gentle Dot Glow`). It is transparent, undecorated, not focusable, out of the taskbar, and ignores cursor events. Its NSWindow sits at level 102, above menus, with collection behavior `canJoinAllSpaces | stationary | ignoresCycle | fullScreenAuxiliary`. It is ordered in with `orderFrontRegardless` when a session starts, so it never becomes key or activates the app, and ordered out when the session ends. A thread of its own receives the marks and drops any that arrive after the session ended. That thread looks up the display (`CGDisplayBounds`), moves the overlay over the whole display, and emits `computer://glow` to that window only. The UI also ignores marks that come after a `computer://state` without a session.
+ - Working edge: a separate non-fading layer lights a thin neon line along the top edge of the controlled display, with a light traveling along it like the light on the rose's strokes, during a prepared tool call, not for the entire 30-minute authorization. No text or logo. With "Reduce motion" the edge stays lit and the traveling light is left out. The overlay covers the controlled display before a call starts, even before its first action mark. An internal `computer://working {active, operationId}` event targets only the glow; a matching rendered-readiness acknowledgement (`computer_working_ready`, granted only to the glow window) is required before the interactive windows are temporarily hidden. Stale acknowledgements or queued preparation cannot hide windows after cancellation. The working edge clears when the call or session ends.
- Guards and screenshots: the overlay is a Gentle Dot window covering the display, so pointer-owner resolution skips it by its window number (`kCGWindowNumber`) and nothing else. The panel and the Dot still resolve to Gentle Dot and are refused. When the system-wide Accessibility hit test lands on the overlay while another app owns the window under the point, the risk check hit-tests that app's own element instead (`AXUIElementCreateApplication`). Screenshots leave the overlay out with every other window of our process (ScreenCaptureKit `excludingWindows`). The overlay is on screen for the whole session, so it is in the capture's window list before it draws anything.
Why enforcement lives in the app: everything inside the engine, and the daemon's WebSocket, is within the agent's reach (it has a shell, and with the daemon's access key it could answer its own approval cards, L49). The session grant, panic stop, blocklist, rate limit, and risky-action confirmations therefore run in the helper, behind native dialogs the agent cannot answer, and the in-engine guard adds nothing for these tools. macOS also attributes Accessibility and Screen Recording to the app that holds them, Gentle Dot.app. The key in `mcp.json` only reaches the helper, which still asks the user before anything happens.
diff --git a/odd/tasks/computer-working-rings.md b/odd/tasks/computer-working-rings.md
new file mode 100644
index 0000000..98dc24e
--- /dev/null
+++ b/odd/tasks/computer-working-rings.md
@@ -0,0 +1,45 @@
+# Pink working rings without desktop obstruction
+Branch: `feat/computer-working-rings`; baseline: `535e7f7d4bccb83ea4ab7759ef4b97e2622e1208`; isolated worktree: `.cache/computer-working-rings` in the external gentle-assistant clone.
+Delivery: single-pr (explicit user choice), local only; forecast ~650 authored diff lines including tests. Runners: offline Cargo with existing sherpa libraries, installed Vitest/TypeScript, isolated native app probe; no dependency installation.
+
+## Specs
+- S1 — "y sino mas facil, durante esa accion hacer que gentle dot no se vea y reemplazarlo por otra cosa, en algun lado de la pantalla mostrando que esta trabajando". Temporarily hide the Dot and panel for a screenshot-producing/action call or entire batch, from preparation before capture/input until the final capture. Restore previous visibility afterwards without persisting preferences or activating the app. Do not hide for `list_apps` or a denied session grant.
+- S2 — (superseded visual, see S8) "no no, no indicador compacto de texto, sino unos circulos dando vuelta o algo asi en la parte superior de la pantalla, con el mismo estilo que el glow rosa que ya tenemos". Reuse the click-through, nonfocusable, screenshot-excluded glow for pink animated rings/arcs near the top of the controlled display, no text/banner. Rings remain visible through action-mark fading. Follow existing reduced-motion convention with a static illuminated state. Placement on the current controlled display is the proposed implementation default, not permission to cover usable controls.
+- S3 — "me gusta la de contenido oculto". Preserve exclusion of own panel contents from model screenshots; do not expose chat/settings. No change to JPEG quality65, max long-edge1280 or coordinate mapping.
+- S4 — Accepted proposal: "El guard permanecería intacto." Do not weaken blocklist, consent, permission checks, risky confirmations, epoch/Stop/panic or target guards. Existing tray Stop and panic remain available; their native operation is a verification obligation, not an assumed pass.
+- S5 — Accepted proposal: "No aceptaría continuar silenciosamente si falla la ocultación. Si no podemos confirmar un estado seguro, no se envía entrada." Confirm indicator readiness and native temporary hiding before executing capture/input. Bound waits, reject stale/late operations, recheck session epoch after preparation, and restore on all normal refusal/error/Stop paths. Do not claim Drop guarantees restoration after process abort or a blocked native UI. Restoration must not steal keyboard focus.
+- S6 — "dale vamos con esa" authorizes implementation and verification in external `/Users/alanbuscaglia/work/gentle-assistant`. Preserve isolation: no accounts/connectors/keychain use, app model calls, remote execution, automatic dependency downloads, auto-answering native permission dialogs or Yolo. Use RED → GREEN for applicable deterministic rules and the existing shared behavior; independently verify security/concurrency changes and repeat isolated native geometry/refusal checks against a harmless local surface. Report unavailable native/full-screen/multi-monitor checks honestly.
+
+- S7 — "probemos antes de pr". Do not open/publish a PR or push before applicable automated, independent and isolated native checks are observed. Missing or failed proof is reported for a human decision, never treated as a pass. Single-pr is delivery organization, not immediate publishing authorization.
+
+- S8 — (superseded visual, see S9) "cambia los circulitos a algo que concuerde mas con la app y el diseño actual". Replace the three spinning arcs with the app's own visual language: a small copy of the Dot (black disc, accent in-control rim, Rose in mood "control") near the top, no text. Reduced motion follows the Dot's existing rule (no traveling light, rose stays lit). Readiness ack, click-through and fences unchanged.
+
+- S9 — "hmm algo mejor, no reusar el logo". Do not reuse the rose/Dot logo. Indicator: thin neon line along the top edge of the controlled display in the rose's neon (#ff2d7a / #ffd6e8) with a traveling light (the app's "traveling light" language), no text or logo. Reduced motion: edge stays lit, traveling light hidden. Ack, click-through and fences unchanged.
+
+## Tasks
+- T1 | S1–S9 | delegated parallel native/UI units with disjoint edit surfaces; parent owns integration/docs/git | done | commit: see L21 | Risk: items2/4 (visible safety and native/IPC ordering), item3 if shared behavior changes | RED/GREEN: pending | Native and independent proof: pending.
+
+## Log
+- L1 — Original implementation authorization verbatim: "dale vamos con esa". Prior investigation-only directions and earlier hidden-content/blocked-area proposal were refined by S1/S2; the selected implementation hides obstructive own UI temporarily rather than painting blocked rectangles.
+- L2 — Native prior reproduction at source HEAD660be8: a1280×720 JPEG at scale2/3 omitted an ordinary Dot window at global1836,504,72,72; click1248,360 resolved to own window and returned `Gentle Dot does not control Gentle Dot. The action was refused.` No real Calendar actions. Preserve this guard.
+- L3 — `main` is not an ancestor of the original feat/gentle-dot HEAD, so the initial ancestry preflight exited1 before creating a worktree. Inspection found `main..HEAD` differs only in two historical task-note lines, no source differences. Created a fresh worktree based on local main; original checkout and notes remain untouched. No merges, resets or remote operations. Existing node_modules linked into worktree; no packages installed.
+- L4 — Writer reason: two independent substantial native lifecycle and UI animation units launched together in the same fresh external-repo worktree, with disjoint surfaces. Parent handles docs and seam verification. A400-line heuristic is not a code/test cap; forecast exceeds it, so delivery strategy must be resolved before a feature commit. No push/PR in scope.
+- L5 — Integration contract: internal `computer://working` event emitted only to glow, payload `{active:boolean, operationId:number}`. UI acknowledges rendered active state via internal `computer_working_ready {operationId}`; native handler must accept only glow window and current pending operation. End/stale events cannot resurrect old indicators or perform late hides. Native preparation, including confirmed hiding, is synchronous to helper but dispatched safely to main/UI threads with bounded cancellation. Parent can adjust this contract only through one coordinated handoff before either side relies on a replacement.
+
+- L6 — Parallel units launched: native N1 `mv4enxjk-4-r8eq`, UI U1 `mv4enxnl-5-jnj9`. Their source surfaces are disjoint; parent alone edits design/feature docs and owns generated builds and Git. Parent updated S24.6/S28 design descriptions provisionally to match the authorized behavior; no verification pass is claimed yet.
+
+- L7 — User selected "Un único cambio integral" (single-pr) in the review-size decision. Keep the coherent feature and tests together; accept the forecast above400 authored lines without artificial splitting. This is local organization only, not authorization to publish a PR or transfer repository data.
+
+- L8 — User requirement verbatim: "probemos antes de pr". Added S7; T1 remains in progress. No remote/publishing actions while writers or functional proof are pending.
+- L9 — Native N1 reported computer::working 13/13 and computer::mcp 72/72 GREEN (worker-observed, not yet rechecked by parent). Its new ACL test was RED because the ack command lacked a Tauri permission. Parent, not the writer, added `computer_working_ready` to build.rs COMMANDS and `allow-computer-working-ready` only to the `glow` capability in capabilities/default.json; dot/panel capabilities unchanged. Runtime label/operation validation in the handler remains required.
+- L10 — Integrated checks: cargo test 406 passed/0 failed exit0; clippy exit0; UI vitest exit0, UI tsc exit0, biome exit0 (6 pre-existing warnings). Full-repo vitest/tsc fail only in daemon project because the worktree does not link packages/daemon node_modules (environmental, unrelated). Release build UI_BUILD=0/TAURI_BUILD=0 (harmless rust-objcopy strip warning), ad hoc signed.
+- L11 — Isolated native probe (job-11, PID 28261, exit0, no clicks/keys, user approved native grant): screenshot OK; Dot 1836,504,72,72 restored after screenshot; during wait(4000) Dot absent from on-screen windows and glow covered 1920x1080 display; Dot restored after wait; frontApp Ghostty unchanged across calls. Glow window stays ordered in while the session is active (pre-existing session-scoped behaviour). Not yet verified: visual appearance of rings (needs human observation), Stop/panic mid-call, multi-monitor, full-screen, panel-visible case.
+- L12 — User request verbatim: "cambia los circulitos a algo que concuerde mas con la app y el diseño actual". Parent (inline, UI-only) replaced arcs with the in-control rose disc. RED: glow.test.tsx 2 failed/17 passed with old arcs; GREEN: packages/ui vitest 24 files 259 tests passed exit0, UI tsc exit0, biome check exit0. design.md S24.6/S28 updated. Rebuild and native visual check pending.
+- L13 — Native probe with the rose (job-13) failed dotRestored checks: its 'before' sample (924,252) was taken while the app was still positioning the Dot at startup; after-call positions matched the default 1836,504 from the first run. Probe fixed to wait for a stable Dot position; rerun job-14 PASS (hidden during call, restored to settled position, front app unchanged, no input).
+- L14 — User request verbatim: "hmm algo mejor, no reusar el logo". Parent replaced the rose with a top-edge neon line + traveling light. RED: 3 failed/16 passed against the rose; GREEN: packages/ui vitest 24 files 259 passed exit0, UI tsc exit0, biome check exit0. design.md updated. Rebuild and visual check pending.
+- L15 — Parent truncated docs/design.md through a whole-file read/write (50KB read cap); restored from baseline and reapplied the two paragraph edits with the edit tool (diff +2/-1). Native probe with the top-edge light (job-16, PID 43123 gone): PASS, all checks true, no input. Visual confirmation by the user pending.
+- L16 — User visual approval verbatim: "mucho mejor, vamos con esa". S9 top-edge light accepted. Remaining: native Stop/panic mid-call check, independent verifier verdict, local commit (no PR/push, S7).
+- L17 — Native panic probe (job-17, PID 45044 gone): wait completed normally after 5344 ms, so no stop was observed; Dot restored; glow still ordered in (consistent with an active session). Cause undetermined: key not pressed in time, global shortcut not registered under isolation, or a real defect. Asked the user.
+- L18 — Independent verifier mv4fai48-6-4tib: no blockers on the final S9 snapshot. S1/S3/S4 PASS; S2/S8/S9 PASS structurally; S5 PASS in unit tests and 8/8 scratch probes (Stop during ack wait, stale ack, hide timeout then late hide, Drop restore on refusal/decline/panic mid-batch, 200-iteration concurrent Stop, happy path, baseline dump identical). Re-ran Rust 406/0, clippy 0, UI 259/259, tsc 0. design.md confirmed +2/-1 only. To commit as regression tests: probes 1, 2, 4, 6 (fewer iterations) and the Control notify -> session_ended wiring. Advisories: screenshot does not recheck still_running between prepare and capture (baseline), panel reopened+closed mid-call is shown again on restore, rAF throttling fails closed, glow test names still say rings, non-macOS build not compile-checked.
+- L19 — User had not pressed the shortcut in job-17 ("no no sabia qeu tenia que hacerlo"). Retry job-18 (PID 46776 gone) with a 15 s batch of waits: PASS — panic ⌥⇧Esc stopped the call early, Dot restored, glow gone, no input.
+- L20 — Verifier probes 1, 2, 4 and 6 committed as `computer::mcp::tests::preparation_races` (concurrent Stop at 50 iterations). Regression tests, written after the behavior existed, so no RED phase: they passed on first run (4/4). Full Rust 410 passed/0 failed/4 ignored, clippy exit0. UI test names moved from "rings" to "edge": UI vitest 259/259, tsc 0, biome 0. Control notify -> session_ended wiring in app.rs remains without a unit test (needs a Tauri app handle); covered natively by job-18.
diff --git a/packages/ui/src/components/GlowSurface.tsx b/packages/ui/src/components/GlowSurface.tsx
index 42ec08b..1a32310 100644
--- a/packages/ui/src/components/GlowSurface.tsx
+++ b/packages/ui/src/components/GlowSurface.tsx
@@ -1,5 +1,12 @@
import { type CSSProperties, useEffect, useRef, useState } from "react";
-import { type ComputerGlow, onComputerGlow, onComputerState } from "../computer.ts";
+import {
+ type ComputerGlow,
+ type ComputerWorking,
+ computerWorkingReady,
+ onComputerGlow,
+ onComputerState,
+ onComputerWorking,
+} from "../computer.ts";
/** The glow stays lit this long after the last action, then fades for `FADE_MS` (about 1.5 s in all). */
const HOLD_MS = 1200;
@@ -54,14 +61,24 @@ function Mark({ glow, still }: { glow: ComputerGlow; still: boolean }) {
* drag, short markers for moves and scrolls, and an outline around the focused element for keys.
* It shows only while the agent acts, fades out about 1.5 s after the last action, and clears at
* once when the session ends. With reduced motion the glow is static: no pulse and no trail.
+ *
+ * While the Dot steps aside for an operation, the top edge of the display glows in the rose's neon
+ * and a light travels along it, apart from the fading marks. Once it is painted the overlay tells
+ * the app, which waits for that before it captures or acts. With reduced motion the edge stays lit
+ * and the traveling light is left out.
*/
export function GlowSurface() {
const [marks, setMarks] = useState<Lit[]>([]);
const [fading, setFading] = useState(false);
const [still] = useState(prefersReducedMotion);
+ const [operation, setOperation] = useState<number>();
const timers = useRef<ReturnType<typeof setTimeout>[]>([]);
const ended = useRef(false);
const next = useRef(0);
+ /** The operation the rings show, kept in step with events before React renders them. */
+ const current = useRef<number | undefined>(undefined);
+ /** The newest operation id seen, started or ended; nothing older shows again. */
+ const latest = useRef(-1);
useEffect(() => {
document.documentElement.dataset.surface = "glow";
@@ -70,10 +87,15 @@ export function GlowSurface() {
for (const timer of timers.current) clearTimeout(timer);
timers.current = [];
};
+ const rest = () => {
+ current.current = undefined;
+ setOperation(undefined);
+ };
const clear = () => {
stopTimers();
setFading(false);
setMarks([]);
+ rest();
};
const show = (glow: ComputerGlow) => {
// A mark that arrives after Stop, panic, or the timeout stays dark.
@@ -88,8 +110,23 @@ export function GlowSurface() {
setTimeout(() => setMarks([]), HOLD_MS + FADE_MS),
];
};
+ const work = ({ active, operationId }: ComputerWorking) => {
+ if (!live) return;
+ if (active) {
+ // A start that is late (its end or a newer operation came first) or that arrives after
+ // Stop, panic, or the timeout stays dark.
+ if (ended.current || operationId <= latest.current) return;
+ latest.current = operationId;
+ current.current = operationId;
+ setOperation(operationId);
+ } else if (operationId >= latest.current) {
+ latest.current = operationId;
+ rest();
+ }
+ };
const subscriptions = [
onComputerGlow(show),
+ onComputerWorking(work),
onComputerState((state) => {
ended.current = state.session === undefined;
if (live && ended.current) clear();
@@ -97,17 +134,36 @@ export function GlowSurface() {
];
return () => {
live = false;
+ current.current = undefined;
stopTimers();
for (const s of subscriptions) void s.then((unlisten) => unlisten());
};
}, []);
+ // The rings are committed by now; the second frame runs once the first one has painted them.
+ useEffect(() => {
+ if (operation === undefined) return;
+ let frame = window.requestAnimationFrame(() => {
+ frame = window.requestAnimationFrame(() => {
+ if (current.current === operation) void computerWorkingReady(operation).catch(() => {});
+ });
+ });
+ return () => window.cancelAnimationFrame(frame);
+ }, [operation]);
+
const className = `glow-layer${fading ? " glow-fading" : ""}${still ? " glow-static" : ""}`;
return (
- <div className={className} aria-hidden="true">
- {marks.map(({ id, glow }) => (
- <Mark key={id} glow={glow} still={still} />
- ))}
- </div>
+ <>
+ <div className={className} aria-hidden="true">
+ {marks.map(({ id, glow }) => (
+ <Mark key={id} glow={glow} still={still} />
+ ))}
+ </div>
+ {operation !== undefined && (
+ <div className={`glow-working${still ? " glow-static" : ""}`} aria-hidden="true">
+ <span className="glow-working-light" />
+ </div>
+ )}
+ </>
);
}
diff --git a/packages/ui/src/computer.ts b/packages/ui/src/computer.ts
index d7fdace..06cc2a6 100644
--- a/packages/ui/src/computer.ts
+++ b/packages/ui/src/computer.ts
@@ -81,7 +81,7 @@ export async function computerStatus(): Promise<ComputerState> {
return stateOf(await invoke<ComputerStateEvent>("computer_status"));
}
-/** The event API, imported once: the glow overlay subscribes to two events at the same time. */
+/** The event API, imported once: the glow overlay subscribes to three events at the same time. */
let eventApi: Promise<typeof import("@tauri-apps/api/event")> | undefined;
function events() {
eventApi ??= import("@tauri-apps/api/event");
@@ -113,6 +113,38 @@ export async function onComputerGlow(handler: (glow: ComputerGlow) => void) {
});
}
+/**
+ * The agent is busy on one operation (a screenshot or an action, or a batch of them) while the Dot
+ * steps aside. Operation ids only grow; the end of an operation carries the same id as its start.
+ */
+export interface ComputerWorking {
+ active: boolean;
+ operationId: number;
+}
+
+/** The overlay window's `computer://working` events; anything malformed is dropped. */
+export async function onComputerWorking(handler: (working: ComputerWorking) => void) {
+ if (!isTauri()) return () => {};
+ const { listen } = await events();
+ return listen<unknown>("computer://working", (event) => {
+ const working = workingOf(event.payload);
+ if (working) handler(working);
+ });
+}
+
+/** Tells the app the working rings for this operation are on screen, so it may go on. */
+export function computerWorkingReady(operationId: number): Promise<unknown> {
+ if (!isTauri()) return Promise.resolve();
+ return invoke("computer_working_ready", { operationId });
+}
+
+function workingOf(payload: unknown): ComputerWorking | undefined {
+ if (typeof payload !== "object" || payload === null) return undefined;
+ const { active, operationId } = payload as Record<string, unknown>;
+ if (typeof active !== "boolean" || typeof operationId !== "number") return undefined;
+ return Number.isSafeInteger(operationId) && operationId >= 0 ? { active, operationId } : undefined;
+}
+
function glowOf(payload: unknown): ComputerGlow | undefined {
if (typeof payload !== "object" || payload === null) return undefined;
const event = payload as Record<string, unknown>;
diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.css
index 68d5092..6c1a667 100644
--- a/packages/ui/src/styles.css
+++ b/packages/ui/src/styles.css
@@ -1544,6 +1544,54 @@ html[data-surface="glow"] body {
}
}
+/* While the Dot steps aside for an operation: the top edge of the controlled display glows in the
+ rose's neon, and a light travels along it, like the light on the rose's strokes. No text, no
+ logo. It sits apart from the fading marks and ignores the pointer. Reduce motion: the edge stays
+ lit and the traveling light is left out (frozen, it would look like a stray spot). */
+.glow-working {
+ position: fixed;
+ top: 0;
+ left: 0;
+ right: 0;
+ height: 3px;
+ overflow: hidden;
+ background: linear-gradient(
+ 90deg,
+ rgba(255, 45, 122, 0.15),
+ rgba(255, 45, 122, 0.55) 50%,
+ rgba(255, 45, 122, 0.15)
+ );
+ box-shadow:
+ 0 0 6px rgba(255, 45, 122, 0.55),
+ 0 0 14px rgba(255, 45, 122, 0.3);
+ border-bottom: 1px solid #ff2d7a;
+ pointer-events: none;
+}
+
+.glow-working-light {
+ position: absolute;
+ top: 0;
+ bottom: 0;
+ left: 0;
+ width: 22%;
+ background: linear-gradient(90deg, transparent, #ffd6e8 50%, transparent);
+ filter: drop-shadow(0 0 4px #ff2d7a);
+ animation: glow-travel 1.6s ease-in-out infinite;
+}
+
+.glow-static .glow-working-light {
+ display: none;
+}
+
+@keyframes glow-travel {
+ from {
+ transform: translateX(-100%);
+ }
+ to {
+ transform: translateX(455%);
+ }
+}
+
/* ---------- Attachments (S31) ---------- */
.visually-hidden {
diff --git a/packages/ui/test/glow.test.tsx b/packages/ui/test/glow.test.tsx
index 8622022..a9d8e7d 100644
--- a/packages/ui/test/glow.test.tsx
+++ b/packages/ui/test/glow.test.tsx
@@ -1,3 +1,5 @@
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
import { act, render, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -5,6 +7,8 @@ const h = vi.hoisted(() => ({
invoke: vi.fn(),
listeners: new Map<string, (event: { payload: unknown }) => void>(),
reducedMotion: false,
+ frames: new Map<number, FrameRequestCallback>(),
+ nextFrame: 0,
}));
vi.mock("@tauri-apps/api/core", () => ({
@@ -28,6 +32,7 @@ function emit(name: string, payload: unknown) {
const glow = (payload: unknown) => emit("computer://glow", payload);
const session = (active: boolean) => emit("computer://state", { active, yolo: false });
+const working = (active: boolean, operationId: number) => emit("computer://working", { active, operationId });
async function renderGlow() {
const view = render(<GlowSurface />);
@@ -36,13 +41,57 @@ async function renderGlow() {
return view.container;
}
+/** The overlay, once it also listens for the agent's working state. */
+async function mountEdge() {
+ const view = render(<GlowSurface />);
+ await waitFor(() => expect(h.listeners.has("computer://glow")).toBe(true));
+ await waitFor(() => expect(h.listeners.has("computer://state")).toBe(true));
+ await waitFor(() => expect(h.listeners.has("computer://working")).toBe(true));
+ return view;
+}
+
+async function renderEdge() {
+ return (await mountEdge()).container;
+}
+
const marks = (root: HTMLElement) => root.querySelectorAll(".glow-mark");
+const edge = (root: HTMLElement) => root.querySelector(".glow-working");
+const readies = () => h.invoke.mock.calls.filter(([command]) => command === "computer_working_ready");
+
+/** Runs the animation frames the browser would paint next, including any they request. */
+function paint(count = 2) {
+ for (let i = 0; i < count; i += 1) {
+ const due = [...h.frames.values()];
+ h.frames.clear();
+ act(() => {
+ for (const callback of due) callback(0);
+ });
+ }
+}
+
+// A variable, so the bundler leaves the stylesheet's path alone.
+const STYLES = "../src/styles.css";
+const stylesheet = () => readFileSync(fileURLToPath(new URL(STYLES, import.meta.url)), "utf8");
+const rule = (css: string, selector: string) =>
+ css.match(new RegExp(`\\n${selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} \\{([^}]*)\\}`))?.[1] ?? "";
+
+const originalFrame = window.requestAnimationFrame;
+const originalCancelFrame = window.cancelAnimationFrame;
beforeEach(() => {
h.invoke.mockReset();
h.invoke.mockImplementation(() => new Promise(() => {}));
h.listeners.clear();
h.reducedMotion = false;
+ h.frames.clear();
+ window.requestAnimationFrame = (callback: FrameRequestCallback) => {
+ h.nextFrame += 1;
+ h.frames.set(h.nextFrame, callback);
+ return h.nextFrame;
+ };
+ window.cancelAnimationFrame = (frame: number) => {
+ h.frames.delete(frame);
+ };
window.matchMedia = ((query: string) => ({
matches: query.includes("reduced-motion") && h.reducedMotion,
media: query,
@@ -53,6 +102,8 @@ beforeEach(() => {
afterEach(() => {
vi.useRealTimers();
+ window.requestAnimationFrame = originalFrame;
+ window.cancelAnimationFrame = originalCancelFrame;
window.history.replaceState(null, "", "/");
});
@@ -147,6 +198,158 @@ describe("GlowSurface (S28)", () => {
expect([end.style.left, end.style.top]).toEqual(["400px", "500px"]);
});
+ it("runs a neon light along the top edge while the agent works, with no text or logo, until that operation ends", async () => {
+ const root = await renderEdge();
+ expect(edge(root)).toBeNull();
+ working(true, 1);
+ const shown = edge(root) as HTMLElement;
+ expect(shown).not.toBeNull();
+ expect(shown.querySelector(".glow-working-light")).not.toBeNull();
+ expect(shown.querySelector(".rose, .dot-disc, svg")).toBeNull();
+ expect(shown).toHaveTextContent("");
+ expect(shown.closest('[aria-hidden="true"]')).not.toBeNull();
+ expect(root.querySelector("button, [role], [tabindex]")).toBeNull();
+ working(false, 1);
+ expect(edge(root)).toBeNull();
+ });
+
+ it("tells the app the working edge is up only once it has been painted", async () => {
+ const root = await renderEdge();
+ const seen: boolean[] = [];
+ h.invoke.mockImplementation((command: string) => {
+ if (command === "computer_working_ready") seen.push(edge(root) !== null);
+ return new Promise(() => {});
+ });
+ working(true, 3);
+ expect(readies()).toHaveLength(0);
+ paint(1);
+ expect(readies()).toHaveLength(0);
+ paint(1);
+ expect(readies()).toEqual([["computer_working_ready", { operationId: 3 }]]);
+ expect(seen).toEqual([true]);
+ paint();
+ expect(readies()).toHaveLength(1);
+ });
+
+ it("ignores working events it cannot read", async () => {
+ const root = await renderEdge();
+ for (const payload of [
+ null,
+ 1,
+ { active: true },
+ { operationId: 1 },
+ { active: "yes", operationId: 1 },
+ { active: true, operationId: "1" },
+ { active: true, operationId: -1 },
+ { active: true, operationId: 1.5 },
+ { active: true, operationId: Number.NaN },
+ { active: true, operationId: 2 ** 53 },
+ ]) {
+ emit("computer://working", payload);
+ }
+ paint();
+ expect(edge(root)).toBeNull();
+ expect(readies()).toHaveLength(0);
+ // Zero is a valid operation.
+ working(true, 0);
+ expect(edge(root)).not.toBeNull();
+ });
+
+ it("never lets an older or late operation revive or hide the current one", async () => {
+ const root = await renderEdge();
+ working(true, 2);
+ working(false, 1);
+ expect(edge(root)).not.toBeNull();
+ working(true, 1);
+ paint();
+ expect(readies()).toEqual([["computer_working_ready", { operationId: 2 }]]);
+ working(false, 2);
+ expect(edge(root)).toBeNull();
+ // A start that arrives after its own end stays dark.
+ working(true, 2);
+ expect(edge(root)).toBeNull();
+ // An end that overtakes its start fences that start too.
+ working(false, 4);
+ working(true, 4);
+ working(true, 3);
+ paint();
+ expect(edge(root)).toBeNull();
+ expect(readies()).toHaveLength(1);
+ working(true, 5);
+ expect(edge(root)).not.toBeNull();
+ });
+
+ it("does not acknowledge an operation that ended before the working edge was painted", async () => {
+ const root = await renderEdge();
+ working(true, 1);
+ working(false, 1);
+ paint();
+ expect(edge(root)).toBeNull();
+ expect(readies()).toHaveLength(0);
+ });
+
+ it("clears the working edge when the session ends, and a late start stays dark until the next session", async () => {
+ const root = await renderEdge();
+ session(true);
+ working(true, 1);
+ session(false);
+ paint();
+ expect(edge(root)).toBeNull();
+ expect(readies()).toHaveLength(0);
+ working(true, 2);
+ paint();
+ expect(edge(root)).toBeNull();
+ expect(readies()).toHaveLength(0);
+ session(true);
+ working(true, 3);
+ paint();
+ expect(edge(root)).not.toBeNull();
+ expect(readies()).toEqual([["computer_working_ready", { operationId: 3 }]]);
+ });
+
+ it("drops a pending acknowledgement when the overlay goes away", async () => {
+ const view = await mountEdge();
+ working(true, 1);
+ view.unmount();
+ paint();
+ expect(readies()).toHaveLength(0);
+ });
+
+ it("keeps the working edge lit while the action marks fade", async () => {
+ const root = await renderEdge();
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
+ working(true, 1);
+ glow({ kind: "click", x: 10, y: 10 });
+ expect(root.querySelector(".glow-layer .glow-working")).toBeNull();
+ act(() => vi.advanceTimersByTime(1200));
+ expect(root.querySelector(".glow-layer")).toHaveClass("glow-fading");
+ expect(edge(root)).not.toBeNull();
+ act(() => vi.advanceTimersByTime(300));
+ expect(marks(root)).toHaveLength(0);
+ expect(edge(root)).not.toBeNull();
+ });
+
+ it("keeps the edge lit and still with reduced motion", async () => {
+ h.reducedMotion = true;
+ const root = await renderEdge();
+ working(true, 1);
+ expect(edge(root)).toHaveClass("glow-static");
+ paint();
+ expect(readies()).toHaveLength(1);
+ const css = stylesheet();
+ expect(rule(css, ".glow-static .glow-working-light")).toMatch(/display: none/);
+ });
+
+ it("styles the edge in the rose's neon, click-through, with a light that travels along it", () => {
+ const css = stylesheet();
+ expect(rule(css, ".glow-working")).toMatch(/pointer-events: none/);
+ expect(rule(css, ".glow-working")).toMatch(/top: 0/);
+ expect(rule(css, ".glow-working")).toMatch(/#ff2d7a/);
+ expect(rule(css, ".glow-working-light")).toMatch(/animation: glow-travel/);
+ expect(css).toMatch(/@keyframes glow-travel \{/);
+ expect(css).not.toMatch(/\.glow-ring/);
+ });
+
it("is the app's glow window, which never connects to the assistant", async () => {
window.history.replaceState(null, "", "/?surface=glow");
const view = render(<App />);