Skip to content

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

TypeScript

feat(settings): choose the keyboard shortcut in the app

Alan Buscaglia2d1f5e4b0eeb
diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rs
index dc8b054..171aba7 100644
--- a/apps/desktop/src-tauri/build.rs
+++ b/apps/desktop/src-tauri/build.rs
@@ -24,6 +24,8 @@ const COMMANDS: &[&str] = &[
"voice_model_download",
"voice_model_cancel",
"voice_model_remove",
+ "shortcut_get",
+ "shortcut_set",
];
fn find_in_path(program: &str, path: &str) -> Option<PathBuf> {
diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.json
index 8f69669..7ec1899 100644
--- a/apps/desktop/src-tauri/capabilities/default.json
+++ b/apps/desktop/src-tauri/capabilities/default.json
@@ -40,6 +40,12 @@
"allow-voice-model-remove"
]
},
+ {
+ "identifier": "settings",
+ "description": "The panel's Settings screen (S33): read and change the shortcut that opens the panel; the Dot never changes it.",
+ "windows": ["panel"],
+ "permissions": ["allow-shortcut-get", "allow-shortcut-set"]
+ },
{
"identifier": "glow",
"description": "What the computer-control glow overlay (S28) may call: listening to the glow and session events, nothing else.",
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/shortcut_get.toml b/apps/desktop/src-tauri/permissions/autogenerated/shortcut_get.toml
new file mode 100644
index 0000000..390dd7f
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/shortcut_get.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-shortcut-get"
+description = "Enables the shortcut_get command without any pre-configured scope."
+commands.allow = ["shortcut_get"]
+
+[[permission]]
+identifier = "deny-shortcut-get"
+description = "Denies the shortcut_get command without any pre-configured scope."
+commands.deny = ["shortcut_get"]
diff --git a/apps/desktop/src-tauri/permissions/autogenerated/shortcut_set.toml b/apps/desktop/src-tauri/permissions/autogenerated/shortcut_set.toml
new file mode 100644
index 0000000..d1e0dcf
--- /dev/null
+++ b/apps/desktop/src-tauri/permissions/autogenerated/shortcut_set.toml
@@ -0,0 +1,11 @@
+# Automatically generated - DO NOT EDIT!
+
+[[permission]]
+identifier = "allow-shortcut-set"
+description = "Enables the shortcut_set command without any pre-configured scope."
+commands.allow = ["shortcut_set"]
+
+[[permission]]
+identifier = "deny-shortcut-set"
+description = "Denies the shortcut_set command without any pre-configured scope."
+commands.deny = ["shortcut_set"]
diff --git a/apps/desktop/src-tauri/src/config.rs b/apps/desktop/src-tauri/src/config.rs
index 5296a7f..7aef110 100644
--- a/apps/desktop/src-tauri/src/config.rs
+++ b/apps/desktop/src-tauri/src/config.rs
@@ -70,6 +70,60 @@ pub fn load_config() -> DesktopConfig {
parse_config(dir, file.as_deref(), env)
}
+pub const INVALID_CONFIG: &str =
+ "config.json is not valid JSON, so Gentle Dot left it as it is. Fix or remove it, then try again.";
+
+/// The text of `config.json` with `shortcut` set and every other key kept.
+/// A file that is not a JSON object is refused rather than replaced.
+pub fn with_shortcut(file: Option<&str>, shortcut: &str) -> Result<String, String> {
+ let mut json = match file {
+ Some(text) => serde_json::from_str::<serde_json::Value>(text)
+ .ok()
+ .filter(serde_json::Value::is_object)
+ .ok_or(INVALID_CONFIG)?,
+ None => serde_json::json!({}),
+ };
+ json["shortcut"] = shortcut.into();
+ let text = serde_json::to_string_pretty(&json).map_err(|e| e.to_string())?;
+ Ok(text + "\n")
+}
+
+/// Saves the shortcut in `config.json` (S33.3): read, change one key, then write a private
+/// temporary file and rename it over the old one, so a crash never leaves half a file.
+pub fn save_shortcut(path: &Path, shortcut: &str) -> Result<(), String> {
+ let file = match std::fs::read_to_string(path) {
+ Ok(text) => Some(text),
+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
+ Err(error) => return Err(format!("Gentle Dot cannot read config.json ({error}), so the shortcut was not saved.")),
+ };
+ let text = with_shortcut(file.as_deref(), shortcut)?;
+ write_private(path, &text).map_err(|error| format!("Gentle Dot cannot save config.json ({error})."))
+}
+
+fn write_private(path: &Path, text: &str) -> std::io::Result<()> {
+ use std::io::Write;
+ let dir = path.parent().unwrap_or(Path::new("."));
+ std::fs::create_dir_all(dir)?;
+ let name = path.file_name().and_then(|n| n.to_str()).unwrap_or("config.json");
+ let temp = dir.join(format!(".{name}.{}.tmp", std::process::id()));
+ let mut options = std::fs::OpenOptions::new();
+ options.write(true).create(true).truncate(true);
+ #[cfg(unix)]
+ std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
+ let written = options.open(&temp).and_then(|mut out| {
+ // `mode` only applies to a new file; a leftover temporary file is made private too.
+ #[cfg(unix)]
+ std::fs::set_permissions(&temp, std::os::unix::fs::PermissionsExt::from_mode(0o600))?;
+ out.write_all(text.as_bytes())?;
+ out.sync_all()
+ });
+ let renamed = written.and_then(|()| std::fs::rename(&temp, path));
+ if renamed.is_err() {
+ let _ = std::fs::remove_file(&temp);
+ }
+ renamed
+}
+
pub fn connection_info(port: u16, token: &str) -> ConnectionInfo {
ConnectionInfo {
url: format!("ws://127.0.0.1:{port}/ws"),
@@ -140,6 +194,76 @@ mod tests {
assert_eq!(config.shortcut, DEFAULT_SHORTCUT);
}
+ #[test]
+ fn saving_a_shortcut_keeps_every_other_key() {
+ let text = with_shortcut(Some(r#"{ "port": 5000, "shortcut": "Alt+Space", "workspace": "~", "extra": { "a": [1] } }"#), "Ctrl+Alt+K").unwrap();
+ let json: serde_json::Value = serde_json::from_str(&text).unwrap();
+ assert_eq!(json, serde_json::json!({ "port": 5000, "shortcut": "Ctrl+Alt+K", "workspace": "~", "extra": { "a": [1] } }));
+ let json: serde_json::Value = serde_json::from_str(&with_shortcut(None, "F5").unwrap()).unwrap();
+ assert_eq!(json, serde_json::json!({ "shortcut": "F5" }));
+ }
+
+ #[test]
+ fn an_invalid_file_is_not_overwritten() {
+ assert_eq!(with_shortcut(Some("{ not json"), "F5"), Err(INVALID_CONFIG.to_string()));
+ assert_eq!(with_shortcut(Some("[1, 2]"), "F5"), Err(INVALID_CONFIG.to_string()));
+ }
+
+ #[test]
+ fn parsing_is_unchanged_after_saving_a_shortcut() {
+ // The file the app writes reads back like any hand-written one: port, shortcut, defaults.
+ let text = with_shortcut(Some(r#"{ "port": 5000, "workspace": "~" }"#), "Shift+Super+K").unwrap();
+ let config = parse_config(dir(), Some(&text), env_of(&[]));
+ assert_eq!(config, DesktopConfig { data_dir: dir(), port: 5000, shortcut: "Shift+Super+K".into() });
+ let config = parse_config(dir(), Some(&text), env_of(&[("GENTLE_DOT_PORT", "6000")]));
+ assert_eq!(config.port, 6000);
+ let text = with_shortcut(None, "F5").unwrap();
+ assert_eq!(parse_config(dir(), Some(&text), env_of(&[])).port, DEFAULT_PORT);
+ }
+
+ fn scratch(name: &str) -> PathBuf {
+ let dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("target/test-scratch/config").join(name);
+ let _ = std::fs::remove_dir_all(&dir);
+ std::fs::create_dir_all(&dir).unwrap();
+ dir
+ }
+
+ #[test]
+ fn saves_the_shortcut_privately_in_place() {
+ let dir = scratch("save");
+ let file = dir.join("config.json");
+ std::fs::write(&file, r#"{ "port": 5000 }"#).unwrap();
+ save_shortcut(&file, "Ctrl+Alt+K").unwrap();
+ let json: serde_json::Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
+ assert_eq!(json, serde_json::json!({ "port": 5000, "shortcut": "Ctrl+Alt+K" }));
+ // Nothing else is left in the folder (the temporary file was renamed over the old one).
+ assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1);
+ #[cfg(unix)]
+ {
+ use std::os::unix::fs::PermissionsExt;
+ assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
+ }
+ // A missing file is created.
+ let fresh = scratch("fresh").join("config.json");
+ save_shortcut(&fresh, "F5").unwrap();
+ assert_eq!(parse_config(dir.clone(), std::fs::read_to_string(&fresh).ok().as_deref(), env_of(&[])).shortcut, "F5");
+ }
+
+ #[test]
+ fn a_bad_file_is_reported_and_left_untouched() {
+ let dir = scratch("bad");
+ let file = dir.join("config.json");
+ std::fs::write(&file, "{ not json").unwrap();
+ assert_eq!(save_shortcut(&file, "F5"), Err(INVALID_CONFIG.to_string()));
+ assert_eq!(std::fs::read_to_string(&file).unwrap(), "{ not json");
+ // A folder where the file should be cannot be read as one.
+ let unreadable = scratch("unreadable").join("config.json");
+ std::fs::create_dir_all(&unreadable).unwrap();
+ let error = save_shortcut(&unreadable, "F5").unwrap_err();
+ assert!(error.starts_with("Gentle Dot cannot read config.json"), "{error}");
+ assert!(unreadable.is_dir());
+ }
+
#[test]
fn connection_info_builds_ws_and_web_urls() {
let info = connection_info(4317, "abc_-9");
diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rs
index 37d3440..1ad5481 100644
--- a/apps/desktop/src-tauri/src/lib.rs
+++ b/apps/desktop/src-tauri/src/lib.rs
@@ -8,6 +8,7 @@ pub mod health;
pub mod platform;
pub mod position;
mod shell;
+pub mod shortcut;
pub mod status;
pub mod voice;
diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rs
index 3ebd232..8b2500d 100644
--- a/apps/desktop/src-tauri/src/shell.rs
+++ b/apps/desktop/src-tauri/src/shell.rs
@@ -1,5 +1,6 @@
//! Tauri wiring: windows, commands, tray menu, global shortcut, Dot snapping,
-//! hiding the rose, the full-screen panel, voice input, and the daemon lifecycle (design §9).
+//! hiding the rose, the full-screen panel, voice input, the shortcut chosen in Settings,
+//! and the daemon lifecycle (design §9).
use crate::computer::app as computer;
use crate::computer::session::Reason;
@@ -8,6 +9,7 @@ use crate::daemon::{self, Daemon, RestartOutcome};
use crate::geometry::{self, Rect};
use crate::platform::{self, LaunchRequest, Os, DOT_TITLE, PANEL_TITLE};
use crate::position::{self, DotPosition};
+use crate::shortcut;
use crate::status::{is_template, tray_status, TrayGlyph};
use crate::voice::app as voice;
use std::path::PathBuf;
@@ -26,7 +28,7 @@ use tauri::{
};
use tauri_plugin_autostart::{MacosLauncher, ManagerExt as _};
use tauri_plugin_dialog::{DialogExt, MessageDialogKind};
-use tauri_plugin_global_shortcut::{GlobalShortcutExt, ShortcutState};
+use tauri_plugin_global_shortcut::{GlobalShortcutExt, Shortcut, ShortcutEvent, ShortcutState};
use tauri_plugin_opener::OpenerExt;
const DOT: &str = "dot";
@@ -54,11 +56,20 @@ struct Shell {
panel_spot: Mutex<Option<(i32, i32)>>,
/// While the panel fills the screen (S26.2): its frame before, to restore.
full_screen: Mutex<Option<Rect>>,
+ /// The shortcut that toggles the panel now; `None` while none is bound (native Wayland).
+ shortcut: Mutex<Option<String>>,
}
/// The tray's rose item, relabeled when the rose is hidden or shown.
struct RoseMenuItem(MenuItem<tauri::Wry>);
+/// The tray's "Open" item, whose accelerator label follows the shortcut (S33.3).
+struct OpenMenuItem(MenuItem<tauri::Wry>);
+
+/// On native Wayland the desktop binds `gentle-dot --toggle` itself.
+const DESKTOP_OWNS_SHORTCUTS: &str =
+ "On this desktop, global shortcuts are set in the system keyboard settings: bind `gentle-dot --toggle` there.";
+
/// Where `show_panel` puts the panel.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Placement {
@@ -196,6 +207,81 @@ fn set_panel_fullscreen(app: AppHandle, on: bool) -> CommandResult<bool> {
Ok(full_screen.is_some())
}
+/// Result of `shortcut_get`: the shortcut that opens the panel and the default one.
+#[derive(serde::Serialize)]
+struct ShortcutInfo {
+ shortcut: String,
+ default: String,
+}
+
+/// Result of `shortcut_set`: the shortcut as saved.
+#[derive(serde::Serialize)]
+struct ShortcutChoice {
+ shortcut: String,
+}
+
+#[tauri::command]
+fn shortcut_get(app: AppHandle) -> ShortcutInfo {
+ let shell = app.state::<Shell>();
+ let current = shell.shortcut.lock().unwrap().clone().unwrap_or_else(|| shell.config.shortcut.clone());
+ ShortcutInfo {
+ shortcut: shortcut::normalize(&current).unwrap_or(current),
+ default: DEFAULT_SHORTCUT.to_string(),
+ }
+}
+
+/// Binds, saves, and shows a new panel shortcut at once (S33.3), or says why it cannot.
+#[tauri::command]
+async fn shortcut_set(app: AppHandle, shortcut: String) -> CommandResult<ShortcutChoice> {
+ tauri::async_runtime::spawn_blocking(move || {
+ let shell = app.state::<Shell>();
+ if !shell.places_windows {
+ return Err(DESKTOP_OWNS_SHORTCUTS.to_string());
+ }
+ let mut current = shell.shortcut.lock().unwrap();
+ let host = ShortcutHost { app: &app, config_file: shell.config.data_dir.join("config.json") };
+ let saved = shortcut::apply(&host, current.as_deref(), &shortcut)?;
+ *current = Some(saved.clone());
+ Ok(ShortcutChoice { shortcut: saved })
+ })
+ .await
+ .map_err(err)?
+}
+
+struct ShortcutHost<'a> {
+ app: &'a AppHandle,
+ config_file: PathBuf,
+}
+
+impl shortcut::Host for ShortcutHost<'_> {
+ fn bind_toggle(&self, shortcut: &str) -> Result<(), String> {
+ self.app.global_shortcut().on_shortcut(shortcut, toggle_on_press).map_err(err)
+ }
+
+ fn unbind(&self, shortcut: &str) {
+ if let Err(error) = self.app.global_shortcut().unregister(shortcut) {
+ eprintln!("gentle-dot: cannot release shortcut `{shortcut}`: {error}");
+ }
+ }
+
+ fn save(&self, shortcut: &str) -> Result<(), String> {
+ config::save_shortcut(&self.config_file, shortcut)
+ }
+
+ fn label_tray(&self, shortcut: &str) {
+ label_tray_open(self.app, shortcut);
+ }
+}
+
+/// The accelerator is only a label; one the menu cannot show is left off.
+fn label_tray_open(app: &AppHandle, shortcut: &str) {
+ if let Some(item) = app.try_state::<OpenMenuItem>() {
+ if item.0.set_accelerator(Some(shortcut)).is_err() {
+ let _ = item.0.set_accelerator(None::<&str>);
+ }
+ }
+}
+
#[tauri::command]
fn set_dot_state(app: AppHandle, state: String) -> CommandResult {
let status = tray_status(&state).ok_or_else(|| format!("unknown state `{state}`"))?;
@@ -429,6 +515,7 @@ fn build_tray(app: &AppHandle, config: &DesktopConfig, rose_hidden: bool) -> tau
// The accelerator is only a label here; an unparsable one must not break the menu.
let open = MenuItem::with_id(app, "open", "Open", true, Some(config.shortcut.as_str()))
.or_else(|_| MenuItem::with_id(app, "open", "Open", true, None::<&str>))?;
+ app.manage(OpenMenuItem(open.clone()));
let menu = Menu::new(app)?;
let conversations = conversations_on(std::env::var("GENTLE_DOT_CONVERSATIONS").ok().as_deref());
for id in tray_menu_ids(conversations, cfg!(target_os = "macos")) {
@@ -561,22 +648,27 @@ fn register_panic_shortcut(app: &AppHandle) {
}
}
-fn register_shortcut(app: &AppHandle, shortcut: &str) {
- let handler = |app: &AppHandle, _: &_, event: tauri_plugin_global_shortcut::ShortcutEvent| {
- if event.state() == ShortcutState::Pressed {
- if let Err(error) = toggle_panel(app.clone()) {
- eprintln!("gentle-dot: cannot toggle the panel: {error}");
- }
- }
- };
- if let Err(error) = app.global_shortcut().on_shortcut(shortcut, handler) {
- eprintln!("gentle-dot: shortcut `{shortcut}` is unavailable ({error}); using {DEFAULT_SHORTCUT}");
- if shortcut != DEFAULT_SHORTCUT {
- let _ = app.global_shortcut().on_shortcut(DEFAULT_SHORTCUT, handler);
+/// What the panel shortcut does, at launch and after a change in Settings.
+fn toggle_on_press(app: &AppHandle, _: &Shortcut, event: ShortcutEvent) {
+ if event.state() == ShortcutState::Pressed {
+ if let Err(error) = toggle_panel(app.clone()) {
+ eprintln!("gentle-dot: cannot toggle the panel: {error}");
}
}
}
+/// Binds the configured shortcut, or the default one when it is unavailable. Returns the bound one.
+fn register_shortcut(app: &AppHandle, shortcut: &str) -> Option<String> {
+ match app.global_shortcut().on_shortcut(shortcut, toggle_on_press) {
+ Ok(()) => return Some(shortcut.to_string()),
+ Err(error) => eprintln!("gentle-dot: shortcut `{shortcut}` is unavailable ({error}); using {DEFAULT_SHORTCUT}"),
+ }
+ if shortcut != DEFAULT_SHORTCUT && app.global_shortcut().on_shortcut(DEFAULT_SHORTCUT, toggle_on_press).is_ok() {
+ return Some(DEFAULT_SHORTCUT.to_string());
+ }
+ None
+}
+
/// A launch of `gentle-dot` (usually `--toggle` from a desktop shortcut) reaches the running app.
fn handle_launch(app: &AppHandle, args: &[String]) {
let result = match platform::launch_request(args) {
@@ -612,6 +704,8 @@ pub fn run() {
rose_hidden,
set_rose_hidden,
set_panel_fullscreen,
+ shortcut_get,
+ shortcut_set,
computer::computer_endpoint,
computer::computer_permissions,
computer::computer_request_permission,
@@ -649,6 +743,7 @@ pub fn run() {
rose_hidden: AtomicBool::new(rose_hidden),
panel_spot: Mutex::new(None),
full_screen: Mutex::new(None),
+ shortcut: Mutex::new(None),
});
app.manage(computer::start(&handle));
let (voice_input, voice_model) = voice::start(&handle);
@@ -660,7 +755,11 @@ pub fn run() {
build_windows(&handle, &config, places_windows, rose_hidden)?;
build_tray(&handle, &config, rose_hidden)?;
if places_windows {
- register_shortcut(&handle, &config.shortcut);
+ let bound = register_shortcut(&handle, &config.shortcut);
+ if let Some(bound) = &bound {
+ label_tray_open(&handle, bound);
+ }
+ *app.state::<Shell>().shortcut.lock().unwrap() = bound;
let snap = app.state::<Shell>().snap.clone();
window(&handle, DOT)?.on_window_event(move |event| {
// A move, or a new monitor scale, re-snaps the Dot and restores its size.
@@ -734,6 +833,25 @@ mod tests {
assert_eq!(panel_placement(false, false, true), Placement::Keep);
}
+ #[test]
+ fn the_shortcut_commands_are_registered_and_granted_to_the_panel_only() {
+ let build = include_str!("../build.rs");
+ let capabilities: serde_json::Value =
+ serde_json::from_str(include_str!("../capabilities/default.json")).unwrap();
+ for command in ["shortcut_get", "shortcut_set"] {
+ assert!(build.contains(&format!("\"{command}\",")), "{command} is missing from build.rs");
+ let permission = format!("allow-{}", command.replace('_', "-"));
+ let windows: Vec<&serde_json::Value> = capabilities["capabilities"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .filter(|c| c["permissions"].as_array().unwrap().iter().any(|p| p == permission.as_str()))
+ .flat_map(|c| c["windows"].as_array().unwrap())
+ .collect();
+ assert_eq!(windows, ["panel"], "{permission}");
+ }
+ }
+
#[test]
fn conversations_flag_reads_like_the_daemon() {
assert!(conversations_on(Some("1")));
diff --git a/apps/desktop/src-tauri/src/shortcut.rs b/apps/desktop/src-tauri/src/shortcut.rs
new file mode 100644
index 0000000..80a1190
--- /dev/null
+++ b/apps/desktop/src-tauri/src/shortcut.rs
@@ -0,0 +1,261 @@
+//! The panel shortcut chosen in Settings (S33): which combinations are allowed, their spelling,
+//! and applying a new one without a restart.
+
+use crate::computer::app::PANIC_SHORTCUT;
+use tauri_plugin_global_shortcut::{Code, Modifiers, Shortcut};
+
+pub const UNREADABLE: &str = "Gentle Dot cannot use that key combination. Try another one.";
+pub const NEEDS_MODIFIER: &str =
+ "Add ⌘, ⌥ or ⌃ (Super, Alt or Ctrl), or use a function key (F1–F24). Shift alone would capture your typing.";
+pub const RESERVED_PANIC: &str = "⌥⇧Esc (Alt+Shift+Esc) is reserved for stopping computer control.";
+pub const ESC_ALONE: &str = "Esc alone closes the panel. Add a modifier key or choose another key.";
+pub const TAKEN: &str = "That shortcut is taken by the system or another app.";
+
+const FUNCTION_KEYS: [Code; 24] = [
+ Code::F1,
+ Code::F2,
+ Code::F3,
+ Code::F4,
+ Code::F5,
+ Code::F6,
+ Code::F7,
+ Code::F8,
+ Code::F9,
+ Code::F10,
+ Code::F11,
+ Code::F12,
+ Code::F13,
+ Code::F14,
+ Code::F15,
+ Code::F16,
+ Code::F17,
+ Code::F18,
+ Code::F19,
+ Code::F20,
+ Code::F21,
+ Code::F22,
+ Code::F23,
+ Code::F24,
+];
+
+fn parse(text: &str) -> Option<Shortcut> {
+ let text = text.trim();
+ if text.is_empty() {
+ return None;
+ }
+ text.parse().ok()
+}
+
+/// Whether two spellings name the same keys.
+pub fn same_keys(a: &str, b: &str) -> bool {
+ matches!((parse(a), parse(b)), (Some(a), Some(b)) if a == b)
+}
+
+/// One spelling per combination: modifiers in the order ⌃⌥⇧⌘, then the key
+/// (`K` for KeyK, `1` for Digit1, the key's code name otherwise).
+fn spell(shortcut: &Shortcut) -> String {
+ let mut parts: Vec<String> = [
+ (Modifiers::CONTROL, "Ctrl"),
+ (Modifiers::ALT, "Alt"),
+ (Modifiers::SHIFT, "Shift"),
+ (Modifiers::SUPER, "Super"),
+ ]
+ .into_iter()
+ .filter(|(modifier, _)| shortcut.mods.contains(*modifier))
+ .map(|(_, name)| name.to_string())
+ .collect();
+ let code = shortcut.key.to_string();
+ let key = code.strip_prefix("Key").or_else(|| code.strip_prefix("Digit")).filter(|rest| rest.len() == 1);
+ parts.push(key.map_or_else(|| code.clone(), str::to_string));
+ parts.join("+")
+}
+
+/// Checks a requested shortcut and returns its normal spelling, or why it cannot be used.
+pub fn normalize(text: &str) -> Result<String, String> {
+ let shortcut = parse(text).ok_or(UNREADABLE)?;
+ if shortcut.mods.is_empty() && shortcut.key == Code::Escape {
+ return Err(ESC_ALONE.into());
+ }
+ if parse(PANIC_SHORTCUT) == Some(shortcut) {
+ return Err(RESERVED_PANIC.into());
+ }
+ // Shift alone would take over typing: ⇧K is a capital K in every app.
+ if shortcut.mods.difference(Modifiers::SHIFT).is_empty() && !FUNCTION_KEYS.contains(&shortcut.key) {
+ return Err(NEEDS_MODIFIER.into());
+ }
+ Ok(spell(&shortcut))
+}
+
+/// What applying a shortcut needs from the running app.
+pub trait Host {
+ /// Makes the shortcut toggle the panel; fails when the system or another app holds it.
+ fn bind_toggle(&self, shortcut: &str) -> Result<(), String>;
+ fn unbind(&self, shortcut: &str);
+ /// Saves the shortcut in `config.json`.
+ fn save(&self, shortcut: &str) -> Result<(), String>;
+ /// Shows the shortcut on the tray's "Open" item.
+ fn label_tray(&self, shortcut: &str);
+}
+
+/// Applies a new panel shortcut at once. The new one is bound before the old one is released,
+/// so a refused or unsaved change leaves the old one working. Returns the saved spelling.
+pub fn apply(host: &impl Host, current: Option<&str>, requested: &str) -> Result<String, String> {
+ let shortcut = normalize(requested)?;
+ let rebind = !current.is_some_and(|current| same_keys(current, &shortcut));
+ if rebind {
+ host.bind_toggle(&shortcut).map_err(|_| TAKEN.to_string())?;
+ }
+ if let Err(error) = host.save(&shortcut) {
+ if rebind {
+ host.unbind(&shortcut);
+ }
+ return Err(error);
+ }
+ if let Some(current) = current.filter(|_| rebind) {
+ host.unbind(current);
+ }
+ host.label_tray(&shortcut);
+ Ok(shortcut)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::cell::RefCell;
+
+ #[test]
+ fn normalizes_any_spelling() {
+ assert_eq!(normalize("alt+space"), Ok("Alt+Space".to_string()));
+ assert_eq!(normalize(" Option + Space "), Ok("Alt+Space".to_string()));
+ assert_eq!(normalize("Cmd+Shift+K"), Ok("Shift+Super+K".to_string()));
+ assert_eq!(normalize("super+shift+control+alt+Digit1"), Ok("Ctrl+Alt+Shift+Super+1".to_string()));
+ assert_eq!(normalize("CTRL+ArrowUp"), Ok("Ctrl+ArrowUp".to_string()));
+ assert_eq!(normalize("Command+KeyK"), Ok("Super+K".to_string()));
+ }
+
+ #[test]
+ fn a_normalized_shortcut_reads_back_as_the_same_keys() {
+ for spelling in ["Alt+Space", "Cmd+Shift+K", "ctrl+alt+Digit7", "F5", "Shift+F12", "Super+Slash"] {
+ let normalized = normalize(spelling).unwrap();
+ assert_eq!(normalize(&normalized), Ok(normalized.clone()), "{spelling}");
+ assert!(same_keys(spelling, &normalized), "{spelling}");
+ }
+ }
+
+ #[test]
+ fn refuses_what_it_cannot_read() {
+ for text in ["", " ", "Alt+", "Alt+Shift", "Hyper+K", "Alt+K+J", "Ctrl+Nope"] {
+ assert_eq!(normalize(text), Err(UNREADABLE.to_string()), "{text:?}");
+ }
+ }
+
+ #[test]
+ fn needs_a_modifier_unless_it_is_a_function_key() {
+ assert_eq!(normalize("K"), Err(NEEDS_MODIFIER.to_string()));
+ assert_eq!(normalize("Space"), Err(NEEDS_MODIFIER.to_string()));
+ assert_eq!(normalize("Digit1"), Err(NEEDS_MODIFIER.to_string()));
+ assert_eq!(normalize("F1"), Ok("F1".to_string()));
+ assert_eq!(normalize("f24"), Ok("F24".to_string()));
+ // Shift alone would capture typing (⇧K is a capital K in every app).
+ assert_eq!(normalize("Shift+K"), Err(NEEDS_MODIFIER.to_string()));
+ assert_eq!(normalize("Shift+Space"), Err(NEEDS_MODIFIER.to_string()));
+ assert_eq!(normalize("Shift+F5"), Ok("Shift+F5".to_string()));
+ assert_eq!(normalize("Ctrl+Shift+K"), Ok("Ctrl+Shift+K".to_string()));
+ }
+
+ #[test]
+ fn refuses_the_panic_shortcut_in_any_spelling() {
+ for text in ["Alt+Shift+Escape", "shift+option+esc", "Shift + Alt + ESC"] {
+ assert_eq!(normalize(text), Err(RESERVED_PANIC.to_string()), "{text}");
+ }
+ // Other modifiers with Esc are not the panic shortcut.
+ assert_eq!(normalize("Ctrl+Shift+Escape"), Ok("Ctrl+Shift+Escape".to_string()));
+ }
+
+ #[test]
+ fn refuses_esc_alone() {
+ assert_eq!(normalize("Escape"), Err(ESC_ALONE.to_string()));
+ assert_eq!(normalize("esc"), Err(ESC_ALONE.to_string()));
+ }
+
+ /// Records what `apply` asks of the app, in order.
+ #[derive(Default)]
+ struct FakeHost {
+ taken: Vec<&'static str>,
+ save_error: Option<&'static str>,
+ calls: RefCell<Vec<String>>,
+ }
+
+ impl Host for FakeHost {
+ fn bind_toggle(&self, shortcut: &str) -> Result<(), String> {
+ self.calls.borrow_mut().push(format!("bind {shortcut}"));
+ if self.taken.contains(&shortcut) {
+ Err("HotKey already registered".into())
+ } else {
+ Ok(())
+ }
+ }
+ fn unbind(&self, shortcut: &str) {
+ self.calls.borrow_mut().push(format!("unbind {shortcut}"));
+ }
+ fn save(&self, shortcut: &str) -> Result<(), String> {
+ self.calls.borrow_mut().push(format!("save {shortcut}"));
+ self.save_error.map_or(Ok(()), |error| Err(error.to_string()))
+ }
+ fn label_tray(&self, shortcut: &str) {
+ self.calls.borrow_mut().push(format!("tray {shortcut}"));
+ }
+ }
+
+ fn calls(host: &FakeHost) -> Vec<String> {
+ host.calls.borrow().clone()
+ }
+
+ #[test]
+ fn applies_a_new_shortcut_live_and_releases_the_old_one() {
+ // The changed shortcut is the one that toggles the panel, and the tray's Open item shows it.
+ let host = FakeHost::default();
+ assert_eq!(apply(&host, Some("Alt+Space"), "cmd+shift+k"), Ok("Shift+Super+K".to_string()));
+ assert_eq!(
+ calls(&host),
+ ["bind Shift+Super+K", "save Shift+Super+K", "unbind Alt+Space", "tray Shift+Super+K"]
+ );
+ }
+
+ #[test]
+ fn keeps_the_old_shortcut_when_the_new_one_is_taken() {
+ let host = FakeHost { taken: vec!["Ctrl+Alt+K"], ..FakeHost::default() };
+ assert_eq!(apply(&host, Some("Alt+Space"), "Ctrl+Alt+K"), Err(TAKEN.to_string()));
+ assert_eq!(calls(&host), ["bind Ctrl+Alt+K"]);
+ }
+
+ #[test]
+ fn keeps_the_old_shortcut_when_it_cannot_be_saved() {
+ let host = FakeHost { save_error: Some("config.json is not valid JSON"), ..FakeHost::default() };
+ assert_eq!(apply(&host, Some("Alt+Space"), "Ctrl+Alt+K"), Err("config.json is not valid JSON".to_string()));
+ assert_eq!(calls(&host), ["bind Ctrl+Alt+K", "save Ctrl+Alt+K", "unbind Ctrl+Alt+K"]);
+ }
+
+ #[test]
+ fn refused_combinations_never_reach_the_app() {
+ let host = FakeHost::default();
+ assert_eq!(apply(&host, Some("Alt+Space"), "Alt+Shift+Esc"), Err(RESERVED_PANIC.to_string()));
+ assert_eq!(apply(&host, Some("Alt+Space"), "K"), Err(NEEDS_MODIFIER.to_string()));
+ assert!(calls(&host).is_empty());
+ }
+
+ #[test]
+ fn the_same_keys_in_another_spelling_are_only_saved() {
+ // Binding the shortcut that is already bound would fail as "taken".
+ let host = FakeHost::default();
+ assert_eq!(apply(&host, Some("option+space"), "Alt+Space"), Ok("Alt+Space".to_string()));
+ assert_eq!(calls(&host), ["save Alt+Space", "tray Alt+Space"]);
+ }
+
+ #[test]
+ fn binds_without_releasing_when_nothing_was_bound() {
+ let host = FakeHost::default();
+ assert_eq!(apply(&host, None, "F5"), Ok("F5".to_string()));
+ assert_eq!(calls(&host), ["bind F5", "save F5", "tray F5"]);
+ }
+}
diff --git a/docs/design.md b/docs/design.md
index 7975aad..e72f63e 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -233,7 +233,7 @@ The user changes the main assistant's model from the chat, in the panel and the
### The panel (expanded)
- 420 × 640 px, rounded 20 px, translucent (macOS vibrancy), anchored to the Dot.
-- Header (one continuous chat): the rose glyph and "Gentle Dot", then Accounts, Profiles, Connectors (a plug; also `/connectors`), Hide the rose (an eye) and Full screen (desktop panel only), and Hide as 18 px stroke icons with tooltips. With `features.conversations` on, the conversation title, the conversations list, and New conversation return.
+- Header (one continuous chat): the rose glyph and "Gentle Dot", then Accounts, Profiles, Connectors (a plug; also `/connectors`), Settings (a gear), Hide the rose (an eye) and Full screen (desktop panel only), and Hide as 18 px stroke icons with tooltips. The web UI has no Settings for now. With `features.conversations` on, the conversation title, the conversations list, and New conversation return.
- "Show earlier" at the top of the chat loads the previous page; a subtle "Earlier messages" divider marks where the chat's earlier session ends.
- Body: message list with streaming Markdown and code blocks; activity rows are collapsed one-liners grouped under the assistant turn ("Read 3 files · Ran tests").
- Ask cards: when the agent needs the user, an inline card with the question and buttons (select and confirm) or a text field (input and editor). The Dot turns amber until the user answers.
@@ -308,6 +308,8 @@ When the panel opens, it is placed next to the Dot on the side with more room, a
| `rose_hidden` | — | `true` when the user hid the rose |
| `set_rose_hidden` | `{ "hidden": boolean }` | hides or shows the Dot window, saves the choice, emits `dot://rose`; returns the resulting state |
| `set_panel_fullscreen` | `{ "on": boolean }` | fills the work area of the panel's display, or restores the frame before; returns the resulting state |
+| `shortcut_get` (panel only) | — | `{ "shortcut": "Alt+Space", "default": "Alt+Space" }`: the shortcut that toggles the panel now, in its normal spelling |
+| `shortcut_set` (panel only) | `{ "shortcut": string }` | `{ "shortcut": string }` as saved, or a rejection with a reason for the user (see "Menu bar and shortcut") |
The Dot drags with `getCurrentWindow().startDragging()` (permission `core:window:allow-start-dragging`). After a drag ends (no move events for 300 ms), Rust snaps the Dot, by its real window size, to the nearest monitor edge with a 12 px margin and saves the position in `~/.gentle-dot/desktop.json`; the next launch restores it, or defaults to the right edge, vertically centered.
@@ -322,7 +324,13 @@ The Dot drags with `getCurrentWindow().startDragging()` (permission `core:window
### Menu bar and shortcut
-Tray menu: Open (`⌥ Space`), New conversation (only with `GENTLE_DOT_CONVERSATIONS=1`, read like the daemon reads it), Open in browser, Hide the rose / Show the rose, Restart assistant, Launch at login (check item), Quit. The global shortcut `Alt+Space` (configurable as `shortcut` in `config.json`) toggles the panel. Launch at login uses `tauri-plugin-autostart`; Open in browser uses `tauri-plugin-opener` with `webUrl`.
+Tray menu: Open (`⌥ Space`), New conversation (only with `GENTLE_DOT_CONVERSATIONS=1`, read like the daemon reads it), Open in browser, Hide the rose / Show the rose, Restart assistant, Launch at login (check item), Quit. The global shortcut `Alt+Space` (configurable as `shortcut` in `config.json`, or in the panel's Settings) toggles the panel.
+
+Settings (S33): a gear in the desktop panel header opens a Settings screen styled like Accounts. Its "Keyboard shortcut" section shows the shortcut (⌘ ⌥ ⌃ ⇧ on macOS, names elsewhere); "Change" records the next key combination from the physical key (`code`), Esc alone cancels recording without hiding the panel (the recorder listens in the capture phase and marks the keys it takes as handled), and "Reset to default" sets `Alt+Space`. `shortcut_set` applies it live, with no restart (`src/shortcut.rs`):
+
+- Rules: the accelerator must parse; it needs a modifier unless it is F1–F24; Esc alone and the panic shortcut ⌥⇧Esc (any spelling) are refused. The saved spelling is normal: modifiers as `Ctrl+Alt+Shift+Super`, then the key (`K`, `1`, `Space`, `F5`).
+- Apply: the new shortcut is bound first; if the system or another app holds it, the old one stays and the reason is "That shortcut is taken by the system or another app." Then `shortcut` is saved in `config.json` (read, change that key only, write a 0600 temporary file and rename it; a file that cannot be read or is not a JSON object is reported, never replaced); if saving fails, the new binding is released and the old one stays. Last, the old shortcut is released and the tray's Open item shows the new one.
+- Native Wayland: the desktop owns shortcuts, so `shortcut_set` explains how to bind `gentle-dot --toggle` instead. Launch at login uses `tauri-plugin-autostart`; Open in browser uses `tauri-plugin-opener` with `webUrl`.
### Hiding the rose and full screen (S26)
@@ -356,6 +364,6 @@ On launch, the app checks `GET /health`. If the daemon does not answer, the app
{ "port": 4317, "workspace": "~/Documents", "shortcut": "Alt+Space", "launchAtLogin": false }
```
-All keys are optional. `workspace` is the user's preferred working folder: the engine is told about it but always runs in `<dataDir>/workspace`.
+All keys are optional. `workspace` is the user's preferred working folder: the engine is told about it but always runs in `<dataDir>/workspace`. Changing the shortcut in Settings rewrites `shortcut` and keeps every other key.
Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array), `GENTLE_DOT_CONVERSATIONS` (`1` turns the conversations list on), `GENTLE_DOT_ROTATE_BYTES` (default 20 MB), `GENTLE_DOT_ROTATE_COMPACTIONS` (default 10), `GENTLE_DOT_HISTORY_PAGE` (default 100), `GENTLE_DOT_MCP_CLI` (JSON array: the command line used for connector sign-in, for tests; default the bundled engine's).
diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsx
index 869594e..60d35f4 100644
--- a/packages/ui/src/App.tsx
+++ b/packages/ui/src/App.tsx
@@ -174,6 +174,7 @@ function Assistant({ surface }: { surface: Surface }) {
{...(computer ? { computer } : {})}
{...(desktop && surface === "panel" ? { voiceModel: true } : {})}
{...(desktop && surface === "panel" ? { panelWindow: panel.controls } : {})}
+ {...(desktop && surface === "panel" ? { settings: true } : {})}
{...(upload ? { upload } : {})}
/>
);
diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsx
index 2823ff0..72aefb6 100644
--- a/packages/ui/src/components/ChatSurface.tsx
+++ b/packages/ui/src/components/ChatSurface.tsx
@@ -24,12 +24,14 @@ import {
PlusIcon,
ProfilesIcon,
RoseGlyph,
+ SettingsIcon,
SpeakerIcon,
SpeakerOffIcon,
} from "./icons.tsx";
import { MessageList } from "./MessageList.tsx";
import { ModelPicker } from "./ModelPicker.tsx";
import { ProfilesPanel } from "./ProfilesPanel.tsx";
+import { SettingsPanel } from "./SettingsPanel.tsx";
import { newRequestId, type Send } from "./types.ts";
interface ChatSurfaceProps {
@@ -49,6 +51,8 @@ interface ChatSurfaceProps {
panelWindow?: PanelWindowControls;
/** Sends files to the daemon (S31); without it the composer has no attachments. */
upload?: Uploader;
+ /** The Settings screen (S33.1), in the desktop panel only: its options belong to the app. */
+ settings?: boolean;
}
const CONTINUE_TEXT = "Continue where you left off.";
@@ -79,19 +83,32 @@ export function ChatSurface({
voiceModel,
panelWindow,
upload,
+ settings,
}: ChatSurfaceProps) {
+ const [showSettings, setShowSettings] = useState(false);
const openAccounts = () => {
+ setShowSettings(false);
send({ type: "auth_list" });
dispatch({ type: "accounts", open: true });
};
const openProfiles = () => {
+ setShowSettings(false);
send({ type: "profiles_list" });
dispatch({ type: "profiles", open: true });
};
const openConnectors = () => {
+ setShowSettings(false);
send({ type: "connectors_list" });
dispatch({ type: "connectors", open: true });
};
+ /** Settings is a screen like the others: opening it closes them, except a sign-in waiting for an answer. */
+ const openSettings = () => {
+ if (state.auth.open && !state.auth.flow?.prompt) dispatch({ type: "accounts", open: false });
+ if (state.profiles.open) dispatch({ type: "profiles", open: false });
+ if (state.connectors.open && !state.connectors.flow?.prompt)
+ dispatch({ type: "connectors", open: false });
+ setShowSettings(true);
+ };
const [showConversations, setShowConversations] = useState(false);
const voice = useVoice(state, send);
const attachments = useAttachments(upload);
@@ -126,12 +143,14 @@ export function ChatSurface({
/** Typing means the user is back to the chat; a sign-in waiting for an answer stays. */
const closeOptions = () => {
setShowConversations(false);
+ setShowSettings(false);
if (state.auth.open && !state.auth.flow?.prompt) dispatch({ type: "accounts", open: false });
if (state.profiles.open) dispatch({ type: "profiles", open: false });
if (state.connectors.open && !state.connectors.flow?.prompt)
dispatch({ type: "connectors", open: false });
};
const covered = state.auth.open || state.profiles.open || state.connectors.open;
+ const settingsShown = settings === true && showSettings && !covered;
// One continuous chat unless the daemon turns the conversations list on.
const conversations = state.features.conversations;
const status = statusText(state);
@@ -197,6 +216,18 @@ export function ChatSurface({
<PlusIcon />
</button>
) : null}
+ {settings ? (
+ <button
+ type="button"
+ className="icon"
+ aria-label="Settings"
+ title="Settings"
+ aria-expanded={settingsShown}
+ onClick={() => (settingsShown ? setShowSettings(false) : openSettings())}
+ >
+ <SettingsIcon />
+ </button>
+ ) : null}
{panelWindow ? (
<>
<RoseButton controls={panelWindow} />
@@ -273,7 +304,13 @@ export function ChatSurface({
</main>
) : null}
- <main className="chat-body" hidden={covered}>
+ {settingsShown ? (
+ <main className="chat-body">
+ <SettingsPanel close={() => setShowSettings(false)} />
+ </main>
+ ) : null}
+
+ <main className="chat-body" hidden={covered || settingsShown}>
{/* In the chat's own flow, so messages start below it instead of sliding under it. */}
{needsAccount(state) ? (
<div className="onboarding">
diff --git a/packages/ui/src/components/SettingsPanel.tsx b/packages/ui/src/components/SettingsPanel.tsx
new file mode 100644
index 0000000..d63cc87
--- /dev/null
+++ b/packages/ui/src/components/SettingsPanel.tsx
@@ -0,0 +1,151 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import {
+ formatShortcut,
+ isMac,
+ loadShortcut,
+ recordKey,
+ type ShortcutInfo,
+ saveShortcut,
+} from "../shortcut.ts";
+import "../settings.css";
+
+type Status =
+ | { kind: "idle" }
+ | { kind: "recording" }
+ | { kind: "applying"; shortcut: string }
+ | { kind: "applied" }
+ | { kind: "failed"; reason: string };
+
+function reasonOf(error: unknown): string {
+ if (typeof error === "string" && error) return error;
+ if (error instanceof Error && error.message) return error.message;
+ return "Gentle Dot could not change the shortcut.";
+}
+
+/** The desktop panel's settings (S33.1); for now, the shortcut that opens the panel. */
+export function SettingsPanel({ close }: { close: () => void }) {
+ const mac = isMac();
+ const show = (accelerator: string) => formatShortcut(accelerator, mac);
+ const [info, setInfo] = useState<ShortcutInfo | undefined>(undefined);
+ const [loadFailed, setLoadFailed] = useState(false);
+ const [status, setStatus] = useState<Status>({ kind: "idle" });
+ const live = useRef(true);
+ const prompt = useRef<HTMLSpanElement>(null);
+
+ useEffect(() => {
+ live.current = true;
+ loadShortcut().then(
+ (found) => {
+ if (live.current) setInfo(found);
+ },
+ () => {
+ if (live.current) setLoadFailed(true);
+ },
+ );
+ return () => {
+ live.current = false;
+ };
+ }, []);
+
+ const apply = useCallback((accelerator: string) => {
+ setStatus({ kind: "applying", shortcut: accelerator });
+ saveShortcut(accelerator).then(
+ (saved) => {
+ if (!live.current) return;
+ setInfo((current) => current && { ...current, shortcut: saved });
+ setStatus({ kind: "applied" });
+ },
+ (error: unknown) => {
+ if (live.current) setStatus({ kind: "failed", reason: reasonOf(error) });
+ },
+ );
+ }, []);
+
+ const recording = status.kind === "recording";
+ useEffect(() => {
+ if (!recording) return;
+ prompt.current?.focus();
+ // Captured before the panel's own keys: Esc here cancels recording instead of hiding the
+ // panel, and ⌘⇧F is recorded instead of filling the screen (they skip handled keys).
+ const onKey = (event: KeyboardEvent) => {
+ event.preventDefault();
+ const recorded = recordKey(event);
+ if (recorded.kind === "cancel") setStatus({ kind: "idle" });
+ else if (recorded.kind === "shortcut") apply(recorded.accelerator);
+ };
+ window.addEventListener("keydown", onKey, true);
+ return () => window.removeEventListener("keydown", onKey, true);
+ }, [recording, apply]);
+
+ const applying = status.kind === "applying";
+ return (
+ <section className="accounts settings" aria-label="Settings">
+ <header className="accounts-header">
+ <h2>Settings</h2>
+ <button type="button" className="icon" aria-label="Close settings" onClick={close}>
+ ×
+ </button>
+ </header>
+
+ <section className="provider-section" aria-labelledby="settings-shortcut">
+ <h3 id="settings-shortcut">Keyboard shortcut</h3>
+ <p className="muted">Opens and hides the panel from any app.</p>
+ {loadFailed ? (
+ <p className="settings-error" role="alert">
+ Gentle Dot could not read the current shortcut.
+ </p>
+ ) : null}
+ <div className="shortcut-row">
+ {recording ? (
+ <span ref={prompt} className="shortcut-recording" tabIndex={-1}>
+ Press the new shortcut… Esc cancels.
+ </span>
+ ) : (
+ <kbd className="shortcut-keys">{info ? show(info.shortcut) : "…"}</kbd>
+ )}
+ {recording ? (
+ <button type="button" onClick={() => setStatus({ kind: "idle" })}>
+ Cancel
+ </button>
+ ) : (
+ <button
+ type="button"
+ className="primary"
+ disabled={!info || applying}
+ onClick={() => setStatus({ kind: "recording" })}
+ >
+ Change
+ </button>
+ )}
+ </div>
+ {status.kind === "applying" ? (
+ <p className="muted" role="status">
+ Applying {show(status.shortcut)}…
+ </p>
+ ) : null}
+ {status.kind === "applied" ? (
+ <p className="settings-ok" role="status">
+ Saved. It works right away.
+ </p>
+ ) : null}
+ {status.kind === "failed" ? (
+ <p className="settings-error" role="alert">
+ {status.reason}
+ </p>
+ ) : null}
+ <p className="settings-hint muted">
+ Use at least one modifier key ({mac ? "⌘ ⌥ ⌃ ⇧" : "Super, Alt, Ctrl, Shift"}), or a function key.
+ </p>
+ <button
+ type="button"
+ className="link"
+ title={info ? `Default: ${show(info.default)}` : undefined}
+ disabled={!info || info.shortcut === info.default || applying || recording}
+ onClick={() => info && apply(info.default)}
+ >
+ Reset to default
+ </button>
+ </section>
+ </section>
+ );
+}
diff --git a/packages/ui/src/components/icons.tsx b/packages/ui/src/components/icons.tsx
index 513e553..1da5468 100644
--- a/packages/ui/src/components/icons.tsx
+++ b/packages/ui/src/components/icons.tsx
@@ -212,3 +212,13 @@ export function CollapseIcon() {
</Icon>
);
}
+
+/** A gear: the panel's settings (S33.1). */
+export function SettingsIcon() {
+ return (
+ <Icon>
+ <circle cx="12" cy="12" r="3" />
+ <path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 1 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06A1.65 1.65 0 0 0 4.68 15a1.65 1.65 0 0 0-1.51-1H3a2 2 0 1 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06A1.65 1.65 0 0 0 9 4.68a1.65 1.65 0 0 0 1-1.51V3a2 2 0 1 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06A1.65 1.65 0 0 0 19.4 9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 1 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1z" />
+ </Icon>
+ );
+}
diff --git a/packages/ui/src/settings.css b/packages/ui/src/settings.css
new file mode 100644
index 0000000..5652fd1
--- /dev/null
+++ b/packages/ui/src/settings.css
@@ -0,0 +1,45 @@
+/* Settings screen (SettingsPanel). Uses the shared tokens, the Accounts header, and button styles. */
+
+.shortcut-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ margin: 4px 0 10px;
+ padding: 12px 14px;
+ border-radius: var(--radius-md);
+ border: 1px solid var(--line);
+ background: var(--surface);
+}
+
+.shortcut-keys {
+ font: 600 16px / 24px var(--font-mono);
+ letter-spacing: 0.04em;
+ color: var(--text);
+}
+
+.shortcut-recording {
+ font-size: 13px;
+ color: var(--accent);
+ outline: none;
+}
+
+.shortcut-row:has(.shortcut-recording) {
+ border-color: var(--accent-line);
+ box-shadow: 0 0 0 3px var(--accent-soft);
+}
+
+.settings-ok {
+ color: var(--green);
+}
+
+.settings-error {
+ color: var(--red);
+}
+
+.settings-ok,
+.settings-error,
+.settings .muted {
+ margin: 6px 0;
+ font-size: 12px;
+}
diff --git a/packages/ui/src/shortcut.ts b/packages/ui/src/shortcut.ts
new file mode 100644
index 0000000..0368299
--- /dev/null
+++ b/packages/ui/src/shortcut.ts
@@ -0,0 +1,102 @@
+import { invoke } from "@tauri-apps/api/core";
+
+/** The shortcut that opens the panel, as the desktop app reports it (S33). */
+export interface ShortcutInfo {
+ shortcut: string;
+ default: string;
+}
+
+export function loadShortcut(): Promise<ShortcutInfo> {
+ return invoke<ShortcutInfo>("shortcut_get");
+}
+
+/** Binds and saves a new shortcut; resolves with its saved spelling or rejects with the app's reason. */
+export async function saveShortcut(shortcut: string): Promise<string> {
+ const result = await invoke<{ shortcut: string }>("shortcut_set", { shortcut });
+ return result.shortcut;
+}
+
+export function isMac(userAgent: string = navigator.userAgent): boolean {
+ return /Mac|iPhone|iPad/.test(userAgent);
+}
+
+type Modifier = "Ctrl" | "Alt" | "Shift" | "Super";
+
+/** The macOS order of modifiers (⌃⌥⇧⌘), also used for the accelerator the app saves. */
+const MODIFIERS: { name: Modifier; symbol: string }[] = [
+ { name: "Ctrl", symbol: "⌃" },
+ { name: "Alt", symbol: "⌥" },
+ { name: "Shift", symbol: "⇧" },
+ { name: "Super", symbol: "⌘" },
+];
+
+/** Every spelling the app's accelerator parser accepts for a modifier. */
+function modifierOf(token: string, mac: boolean): Modifier | undefined {
+ switch (token.toLowerCase()) {
+ case "ctrl":
+ case "control":
+ return "Ctrl";
+ case "alt":
+ case "option":
+ return "Alt";
+ case "shift":
+ return "Shift";
+ case "super":
+ case "cmd":
+ case "command":
+ return "Super";
+ case "cmdorctrl":
+ case "cmdorcontrol":
+ case "commandorctrl":
+ case "commandorcontrol":
+ return mac ? "Super" : "Ctrl";
+ default:
+ return undefined;
+ }
+}
+
+function keyLabel(key: string): string {
+ const short = /^(?:Key|Digit)(.)$/.exec(key)?.[1];
+ if (short) return short;
+ if (/^esc(ape)?$/i.test(key)) return "Esc";
+ return key.length === 1 ? key.toUpperCase() : key;
+}
+
+/** An accelerator as the user reads it: macOS symbols on macOS (⌥ Space), names elsewhere (Alt+Space). */
+export function formatShortcut(accelerator: string, mac: boolean): string {
+ const tokens = accelerator
+ .split("+")
+ .map((t) => t.trim())
+ .filter(Boolean);
+ const held = new Set(tokens.map((t) => modifierOf(t, mac)).filter((m) => m !== undefined));
+ const key = keyLabel(tokens.find((t) => modifierOf(t, mac) === undefined) ?? "");
+ const modifiers = MODIFIERS.filter((m) => held.has(m.name));
+ if (!mac) return [...modifiers.map((m) => m.name), key].join("+");
+ const symbols = modifiers.map((m) => m.symbol).join("");
+ return symbols && key.length > 1 ? `${symbols} ${key}` : `${symbols}${key}`;
+}
+
+export type Recorded = { kind: "shortcut"; accelerator: string } | { kind: "waiting" } | { kind: "cancel" };
+
+type KeyPress = Pick<KeyboardEvent, "key" | "code" | "metaKey" | "ctrlKey" | "altKey" | "shiftKey">;
+
+const MODIFIER_KEY = /^(?:Shift|Control|Alt|Meta|OS|CapsLock|Fn)(?:Left|Right)?$/;
+
+/**
+ * Turns a keydown into the app's accelerator (`Ctrl+Alt+K`). The key comes from the physical key
+ * (`code`), since ⌥ changes the typed character on macOS. Esc alone cancels; modifiers alone wait.
+ */
+export function recordKey(event: KeyPress): Recorded {
+ const code = event.code || event.key;
+ if (!code || MODIFIER_KEY.test(code) || MODIFIER_KEY.test(event.key)) return { kind: "waiting" };
+ const held: Record<Modifier, boolean> = {
+ Ctrl: event.ctrlKey,
+ Alt: event.altKey,
+ Shift: event.shiftKey,
+ Super: event.metaKey,
+ };
+ const modifiers = MODIFIERS.filter((m) => held[m.name]).map((m) => m.name);
+ if (code === "Escape" && modifiers.length === 0) return { kind: "cancel" };
+ const key = /^(?:Key|Digit)(.)$/.exec(code)?.[1] ?? code;
+ return { kind: "shortcut", accelerator: [...modifiers, key].join("+") };
+}
diff --git a/packages/ui/test/settings.test.tsx b/packages/ui/test/settings.test.tsx
new file mode 100644
index 0000000..35fa387
--- /dev/null
+++ b/packages/ui/test/settings.test.tsx
@@ -0,0 +1,234 @@
+import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { formatShortcut, recordKey } from "../src/shortcut.ts";
+import { type DotState, initialState } from "../src/store.ts";
+
+/** The Settings screen and its keyboard shortcut (S33), through the panel and mocked Tauri commands. */
+const h = vi.hoisted(() => ({
+ tauri: true,
+ shortcut: "Alt+Space",
+ setResult: undefined as undefined | ((shortcut: string) => Promise<unknown>),
+ invoke: vi.fn(),
+ state: undefined as unknown as DotState,
+}));
+
+vi.mock("@tauri-apps/api/core", () => ({
+ isTauri: () => h.tauri,
+ invoke: (command: string, args?: unknown) => h.invoke(command, args),
+}));
+
+vi.mock("@tauri-apps/api/event", () => ({
+ listen: async () => () => {},
+}));
+
+// As in computer.test.tsx: the panel's other desktop events are not under test.
+vi.mock("../src/desktop.ts", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../src/desktop.ts")>()),
+ onDesktopEvent: async () => () => {},
+}));
+
+vi.mock("../src/useDot.ts", () => ({
+ useDot: () => ({ state: h.state, send: () => {}, dismiss: () => {}, dispatch: () => {} }),
+}));
+
+const MAC_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko)";
+const LINUX_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/605.1.15 (KHTML, like Gecko)";
+
+async function renderApp(search: string) {
+ window.history.replaceState(null, "", `/${search}`);
+ const { App } = await import("../src/App.tsx");
+ return render(<App />);
+}
+
+const invoked = (command: string) => h.invoke.mock.calls.filter(([c]) => c === command);
+
+async function openSettings() {
+ await renderApp("?surface=panel");
+ await userEvent.click(await screen.findByRole("button", { name: "Settings" }));
+ return screen.findByRole("region", { name: "Settings" });
+}
+
+async function startRecording() {
+ await openSettings();
+ await screen.findByText("⌥ Space");
+ await userEvent.click(screen.getByRole("button", { name: "Change" }));
+ await screen.findByText(/Press the new shortcut/);
+}
+
+beforeEach(() => {
+ h.tauri = true;
+ h.shortcut = "Alt+Space";
+ h.setResult = undefined;
+ h.state = { ...initialState, connection: "open", agentState: "idle" };
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(MAC_AGENT);
+ h.invoke = vi.fn(async (command: string, args?: Record<string, unknown>) => {
+ switch (command) {
+ case "connection_info":
+ return new Promise(() => {});
+ case "shortcut_get":
+ return { shortcut: h.shortcut, default: "Alt+Space" };
+ case "shortcut_set": {
+ const shortcut = String(args?.shortcut);
+ if (h.setResult) return h.setResult(shortcut);
+ h.shortcut = shortcut;
+ return { shortcut };
+ }
+ default:
+ return null;
+ }
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ window.history.replaceState(null, "", "/");
+ window.sessionStorage.clear();
+});
+
+describe("showing a shortcut", () => {
+ it("uses the macOS symbols on macOS", () => {
+ expect(formatShortcut("Alt+Space", true)).toBe("⌥ Space");
+ expect(formatShortcut("Shift+Super+K", true)).toBe("⇧⌘K");
+ expect(formatShortcut("Ctrl+Alt+Shift+Super+1", true)).toBe("⌃⌥⇧⌘1");
+ // Any spelling of config.json shows the same way, in the macOS order.
+ expect(formatShortcut("cmd+shift+k", true)).toBe("⇧⌘K");
+ expect(formatShortcut("F5", true)).toBe("F5");
+ expect(formatShortcut("Ctrl+Escape", true)).toBe("⌃ Esc");
+ });
+
+ it("uses key names elsewhere", () => {
+ expect(formatShortcut("Alt+Space", false)).toBe("Alt+Space");
+ expect(formatShortcut("Shift+Super+K", false)).toBe("Shift+Super+K");
+ expect(formatShortcut("control+option+k", false)).toBe("Ctrl+Alt+K");
+ });
+});
+
+describe("recording a key combination", () => {
+ const key = (init: Partial<KeyboardEvent>) =>
+ recordKey({ key: "", code: "", metaKey: false, ctrlKey: false, altKey: false, shiftKey: false, ...init });
+
+ it("turns modifiers and the key into the app's accelerator, by physical key", () => {
+ // ⌥K types "˚" on a US Mac; the shortcut is still ⌥K.
+ expect(key({ key: "˚", code: "KeyK", altKey: true })).toEqual({ kind: "shortcut", accelerator: "Alt+K" });
+ expect(key({ key: "!", code: "Digit1", ctrlKey: true, shiftKey: true, metaKey: true })).toEqual({
+ kind: "shortcut",
+ accelerator: "Ctrl+Shift+Super+1",
+ });
+ expect(key({ key: " ", code: "Space", altKey: true })).toEqual({
+ kind: "shortcut",
+ accelerator: "Alt+Space",
+ });
+ expect(key({ key: "F5", code: "F5" })).toEqual({ kind: "shortcut", accelerator: "F5" });
+ });
+
+ it("keeps waiting while only modifiers are held", () => {
+ expect(key({ key: "Alt", code: "AltLeft", altKey: true })).toEqual({ kind: "waiting" });
+ expect(key({ key: "Meta", code: "MetaRight", metaKey: true })).toEqual({ kind: "waiting" });
+ expect(key({ key: "Shift", code: "ShiftLeft", shiftKey: true })).toEqual({ kind: "waiting" });
+ });
+
+ it("cancels on Esc alone", () => {
+ expect(key({ key: "Escape", code: "Escape" })).toEqual({ kind: "cancel" });
+ expect(key({ key: "Escape", code: "Escape", ctrlKey: true })).toEqual({
+ kind: "shortcut",
+ accelerator: "Ctrl+Escape",
+ });
+ });
+});
+
+describe("the Settings screen (S33.1)", () => {
+ it("opens from a gear in the desktop panel header", async () => {
+ const settings = await openSettings();
+ expect(settings).toHaveTextContent("Keyboard shortcut");
+ expect(await screen.findByText("⌥ Space")).toBeInTheDocument();
+ await userEvent.click(screen.getByRole("button", { name: "Close settings" }));
+ expect(screen.queryByRole("region", { name: "Settings" })).toBeNull();
+ });
+
+ it("the web UI shows no gear", async () => {
+ h.tauri = false;
+ await renderApp("?surface=web#token=abc");
+ await screen.findByRole("button", { name: "Accounts" });
+ expect(screen.queryByRole("button", { name: "Settings" })).toBeNull();
+ expect(invoked("shortcut_get")).toHaveLength(0);
+ });
+
+ it("shows key names off macOS", async () => {
+ vi.spyOn(navigator, "userAgent", "get").mockReturnValue(LINUX_AGENT);
+ h.shortcut = "Shift+Super+K";
+ await openSettings();
+ expect(await screen.findByText("Shift+Super+K")).toBeInTheDocument();
+ });
+});
+
+describe("changing the shortcut (S33.2, S33.3)", () => {
+ it("records the next combination and applies it", async () => {
+ await startRecording();
+ fireEvent.keyDown(window, { key: "˚", code: "KeyK", altKey: true, ctrlKey: true });
+ await waitFor(() => expect(invoked("shortcut_set")).toHaveLength(1));
+ expect(invoked("shortcut_set")[0]?.[1]).toEqual({ shortcut: "Ctrl+Alt+K" });
+ expect(await screen.findByText("⌃⌥K")).toBeInTheDocument();
+ expect(screen.getByRole("status")).toHaveTextContent("Saved. It works right away.");
+ });
+
+ it("shows that the change is pending until the app answers", async () => {
+ let answer: (value: unknown) => void = () => {};
+ h.setResult = () => new Promise((resolve) => (answer = resolve));
+ await startRecording();
+ fireEvent.keyDown(window, { key: "k", code: "KeyK", metaKey: true, shiftKey: true });
+ expect(await screen.findByRole("status")).toHaveTextContent("Applying ⇧⌘K…");
+ await act(async () => answer({ shortcut: "Shift+Super+K" }));
+ expect(screen.getByRole("status")).toHaveTextContent("Saved. It works right away.");
+ });
+
+ it("Esc cancels recording without hiding the panel", async () => {
+ await startRecording();
+ fireEvent.keyDown(window, { key: "Escape", code: "Escape" });
+ await waitFor(() => expect(screen.queryByText(/Press the new shortcut/)).toBeNull());
+ expect(invoked("hide_panel")).toHaveLength(0);
+ expect(invoked("shortcut_set")).toHaveLength(0);
+ expect(screen.getByText("⌥ Space")).toBeInTheDocument();
+ // Not recording any more: the next Esc hides the panel as usual.
+ fireEvent.keyDown(window, { key: "Escape", code: "Escape" });
+ expect(invoked("hide_panel")).toHaveLength(1);
+ });
+
+ it("keys pressed while recording do nothing else in the panel", async () => {
+ await startRecording();
+ // ⌘⇧F would toggle full screen.
+ fireEvent.keyDown(window, { key: "f", code: "KeyF", metaKey: true, shiftKey: true });
+ await waitFor(() => expect(invoked("shortcut_set")).toHaveLength(1));
+ expect(invoked("set_panel_fullscreen")).toHaveLength(0);
+ });
+
+ it("keeps recording while only modifiers are held", async () => {
+ await startRecording();
+ fireEvent.keyDown(window, { key: "Alt", code: "AltLeft", altKey: true });
+ expect(screen.getByText(/Press the new shortcut/)).toBeInTheDocument();
+ expect(invoked("shortcut_set")).toHaveLength(0);
+ });
+
+ it("shows the app's reason when it refuses a shortcut and keeps the current one", async () => {
+ h.setResult = async () => {
+ throw "That shortcut is taken by the system or another app.";
+ };
+ await startRecording();
+ fireEvent.keyDown(window, { key: " ", code: "Space", metaKey: true });
+ expect(await screen.findByRole("alert")).toHaveTextContent(
+ "That shortcut is taken by the system or another app.",
+ );
+ expect(screen.getByText("⌥ Space")).toBeInTheDocument();
+ });
+
+ it("resets to the default shortcut", async () => {
+ h.shortcut = "Shift+Super+K";
+ await openSettings();
+ await screen.findByText("⇧⌘K");
+ await userEvent.click(screen.getByRole("button", { name: "Reset to default" }));
+ await waitFor(() => expect(invoked("shortcut_set")).toHaveLength(1));
+ expect(invoked("shortcut_set")[0]?.[1]).toEqual({ shortcut: "Alt+Space" });
+ expect(await screen.findByText("⌥ Space")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Reset to default" })).toBeDisabled();
+ });
+});