hex/src/context.rs
Luke Parker 8efd9909bd
feat: Windows beta with streaming dictation, Hold/Toggle shortcut mode, and x64 + ARM64 release (#141)
* feat: Windows beta with streaming dictation, Hold/Toggle shortcut mode, and release pipeline

Ports the windows-shell branch onto main, adds a GPU streaming finish for Parakeet Unified English with a whole-clip fallback, a cross-platform Hold/Toggle shortcut mode, x64 and ARM64 Windows CI and release feeds, and the website Windows download.

* copy: Enabled/Disabled status on Linux and in the shared Activity labels

* ci: install SPIRV-Headers for the x64 Vulkan build and gate the Windows-only device query

* refactor: one implementation per concept across macOS, Linux, and Windows

The Windows port carried its own copies of modules main already has. Each
concept now has one implementation:

- UI: Windows uses main's design system (design_tokens, desktop_ui,
  text_input, desktop_transcription_picker types) instead of a Fluent copy.
  Windows-only bits are small cfg additions: Segoe Fluent Icons for Icon,
  Windows text-editing key bindings, fixed-height and read-only text inputs,
  and the shared slider_track component. windows_ui keeps the window chrome
  and the anchored dropdowns, now drawn with menu/menu_item.
- Windows chrome: the sidebar runs the full window height as on macOS. The
  caption row is split: the brand sits over the sidebar, the window buttons
  over the content, and both halves stay OS drag regions.
- Commands: Windows uses main's commands, command_grammar, context, keys,
  and personal_commands. The SDK provisioner accepts the embedded TypeScript
  src layout; Windows execute() opens URLs and paths with ShellExecuteW.
- OpenCode: dictation_processor is the one client and ordered policy
  (corrections, rewrite, transformations) on macOS and Windows. Windows keeps
  its opencode2 api CLI transport in a cfg'd submodule; the ranked catalog,
  prompts, Voice Action generation, and the transformation stage are shared.
- desktop_activity is shared; the Windows Settings contract is
  windows_desktop_host, without #[path] aliases.
- self_update is the signed-feed core for both the Linux and Windows
  updaters.
- Windows copy follows the design system: sentence case and "Hex".

* chore(windows): flat app icon that stays crisp at taskbar sizes

* chore: mark the Windows-only screens to consolidate with app_window after #138

* fix(linux): wait for partial X11 grabs to be released before reporting a conflict
2026-10-19 11:00:46 +10:00

373 lines
12 KiB
Rust

#[cfg(target_os = "macos")]
use std::process::{Command, Stdio};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::mpsc::{self, Receiver, TrySendError};
use std::thread;
use std::time::Duration;
#[cfg(target_os = "macos")]
use std::time::Instant;
use color_eyre::eyre::Result;
#[cfg(target_os = "macos")]
use color_eyre::eyre::WrapErr;
#[cfg(any(target_os = "macos", test))]
use color_eyre::eyre::eyre;
use url::Url;
#[cfg(target_os = "macos")]
use objc2::rc::autoreleasepool;
#[cfg(target_os = "macos")]
use objc2_app_kit::NSWorkspace;
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ContextSnapshot {
pub application: Option<String>,
pub browser_url: Option<Url>,
pub window_title: Option<String>,
pub selected_text: Option<String>,
pub input_revision: Option<u64>,
}
pub struct ContextMonitor {
pub updates: Receiver<ContextSnapshot>,
stop: Arc<AtomicBool>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ContextSelector {
Always,
BrowserHost(String),
Application(String),
}
impl ContextSelector {
pub fn application(application: impl Into<String>) -> Self {
Self::Application(application.into())
}
pub fn browser_host(host: impl Into<String>) -> Self {
Self::BrowserHost(normalize_browser_host(&host.into()))
}
pub fn matches(&self, context: &ContextSnapshot) -> bool {
match self {
Self::Always => true,
Self::BrowserHost(host) => context.browser_host_is(host),
Self::Application(application) => context.application_is(application),
}
}
pub fn is_browser(&self) -> bool {
matches!(self, Self::BrowserHost(_))
}
pub(crate) fn specificity(&self) -> u8 {
match self {
Self::Always => 0,
Self::Application(_) => 1,
Self::BrowserHost(_) => 2,
}
}
pub(crate) fn can_coexist_with(&self, other: &Self) -> bool {
match (self, other) {
(Self::Always, _) | (_, Self::Always) => true,
(Self::BrowserHost(left), Self::BrowserHost(right)) => browser_hosts_equal(left, right),
(Self::Application(left), Self::Application(right)) => {
application_names_equal(left, right)
}
(Self::BrowserHost(_), Self::Application(_))
| (Self::Application(_), Self::BrowserHost(_)) => true,
}
}
}
impl ContextMonitor {
pub fn start() -> Self {
Self::start_with_capture(ContextSnapshot::capture, Duration::from_millis(500))
}
fn start_with_capture(
mut capture: impl FnMut() -> Result<ContextSnapshot> + Send + 'static,
poll_interval: Duration,
) -> Self {
let (sender, updates) = mpsc::sync_channel(1);
let stop = Arc::new(AtomicBool::new(false));
let worker_stop = stop.clone();
thread::spawn(move || {
let mut previous = None;
let mut previous_error = None;
while !worker_stop.load(Ordering::Acquire) {
match capture() {
Ok(context) => {
previous_error = None;
if !publish_context(&sender, &mut previous, context) {
break;
}
}
Err(error) => {
let error = error.to_string();
if previous_error.as_ref() != Some(&error) {
tracing::warn!(%error, "could not capture foreground context");
previous_error = Some(error);
}
if !publish_context(&sender, &mut previous, ContextSnapshot::default()) {
break;
}
}
}
thread::sleep(poll_interval);
}
});
Self { updates, stop }
}
}
fn publish_context(
sender: &mpsc::SyncSender<ContextSnapshot>,
previous: &mut Option<ContextSnapshot>,
context: ContextSnapshot,
) -> bool {
if previous.as_ref() == Some(&context) {
return true;
}
match sender.try_send(context.clone()) {
Ok(()) => *previous = Some(context),
Err(TrySendError::Full(_)) => {}
Err(TrySendError::Disconnected(_)) => return false,
}
true
}
impl Drop for ContextMonitor {
fn drop(&mut self) {
self.stop.store(true, Ordering::Release);
}
}
impl ContextSnapshot {
#[cfg(target_os = "macos")]
pub fn capture() -> Result<Self> {
capture_macos()
}
#[cfg(not(target_os = "macos"))]
pub fn capture() -> Result<Self> {
Ok(Self::default())
}
pub fn browser_host(&self) -> Option<&str> {
self.browser_url.as_ref().and_then(Url::host_str)
}
pub fn browser_host_is(&self, host: &str) -> bool {
// Brave is the first macOS browser adapter; Windows reads any
// browser's URL through UI Automation. Command semantics intentionally
// depend on browser host, not this application name.
(cfg!(not(target_os = "macos")) || self.application.as_deref() == Some("Brave Browser"))
&& self
.browser_host()
.is_some_and(|current| browser_hosts_equal(current, host))
}
pub fn application_is(&self, application: &str) -> bool {
self.application
.as_deref()
.is_some_and(|current| application_names_equal(current, application))
}
pub fn label(&self) -> String {
match (&self.application, self.browser_host()) {
(Some(application), Some(host)) => format!("{application} · {host}"),
(Some(application), None) => application.clone(),
_ => "unknown context".into(),
}
}
}
#[cfg(target_os = "macos")]
fn capture_macos() -> Result<ContextSnapshot> {
let (application, pid) = autoreleasepool(|_| {
let application = NSWorkspace::sharedWorkspace()
.frontmostApplication()
.ok_or_else(|| eyre!("macOS did not report a foreground application"))?;
let name = application
.localizedName()
.map(|name| name.to_string())
.ok_or_else(|| eyre!("the foreground application has no display name"))?;
Ok::<_, color_eyre::Report>((name, application.processIdentifier()))
})?;
let browser_url = if application == "Brave Browser" {
capture_brave_url()?
} else {
None
};
Ok(ContextSnapshot {
application: Some(application),
browser_url,
window_title: crate::accessibility::focused_window_title(pid),
selected_text: None,
input_revision: None,
})
}
#[cfg(target_os = "macos")]
pub fn frontmost_bundle_identifier() -> Option<String> {
autoreleasepool(|_| {
NSWorkspace::sharedWorkspace()
.frontmostApplication()?
.bundleIdentifier()
.map(|identifier| identifier.to_string())
})
}
#[cfg(target_os = "macos")]
fn capture_brave_url() -> Result<Option<Url>> {
const CAPTURE_TIMEOUT: Duration = Duration::from_secs(2);
let mut child = Command::new("/usr/bin/osascript")
.args(["-e", BRAVE_URL_SCRIPT])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.wrap_err("could not inspect the active Brave tab")?;
let started = Instant::now();
loop {
if child
.try_wait()
.wrap_err("could not inspect the active Brave tab")?
.is_some()
{
break;
}
if started.elapsed() >= CAPTURE_TIMEOUT {
let _ = child.kill();
let _ = child.wait();
return Err(eyre!("active Brave tab inspection timed out"));
}
thread::sleep(Duration::from_millis(10));
}
let output = child
.wait_with_output()
.wrap_err("could not inspect the active Brave tab")?;
if !output.status.success() {
return Err(eyre!(
"active Brave tab inspection failed: {}",
String::from_utf8_lossy(&output.stderr).trim()
));
}
let url = String::from_utf8_lossy(&output.stdout);
Ok(Url::parse(url.trim()).ok())
}
fn normalize_browser_host(host: &str) -> String {
host.trim_end_matches('.').to_ascii_lowercase()
}
fn application_names_equal(left: &str, right: &str) -> bool {
strip_bundle_extension(left).eq_ignore_ascii_case(strip_bundle_extension(right))
}
/// Removes a trailing `.app` from an application name.
///
/// `NSFileManager.displayNameAtPath` honors Finder's "Show all filename
/// extensions" preference and then returns `Ghostty.app`, while the frontmost
/// application's `localizedName` is always `Ghostty`. Names are normalized
/// before they are stored and again when compared so settings written by
/// either form keep matching.
pub fn strip_bundle_extension(name: &str) -> &str {
let bytes = name.as_bytes();
match bytes.len().checked_sub(4) {
Some(split) if split > 0 && bytes[split..].eq_ignore_ascii_case(b".app") => &name[..split],
_ => name,
}
}
pub(crate) fn browser_hosts_equal(left: &str, right: &str) -> bool {
left.trim_end_matches('.')
.eq_ignore_ascii_case(right.trim_end_matches('.'))
}
#[cfg(target_os = "macos")]
const BRAVE_URL_SCRIPT: &str = r#"
tell application "Brave Browser"
if (count of windows) > 0 then return URL of active tab of front window
end tell
return ""
"#;
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::AtomicUsize;
#[test]
fn application_matching_ignores_process_name_capitalization() {
let context = ContextSnapshot {
application: Some("zed".into()),
..ContextSnapshot::default()
};
assert!(ContextSelector::application("Zed").matches(&context));
}
#[test]
fn application_matching_ignores_finder_bundle_extensions() {
let context = ContextSnapshot {
application: Some("Ghostty".into()),
..ContextSnapshot::default()
};
assert!(ContextSelector::application("Ghostty.app").matches(&context));
assert!(ContextSelector::application("ghostty.APP").matches(&context));
}
#[test]
fn bundle_extension_stripping_only_removes_a_trailing_suffix() {
assert_eq!(strip_bundle_extension("Ghostty.app"), "Ghostty");
assert_eq!(
strip_bundle_extension("T3 Code (Nightly).app"),
"T3 Code (Nightly)"
);
assert_eq!(strip_bundle_extension("Ghostty"), "Ghostty");
assert_eq!(strip_bundle_extension("app.application"), "app.application");
assert_eq!(strip_bundle_extension(".app"), ".app");
}
#[test]
fn monitor_invalidates_stale_context_after_capture_failure() {
let captured = ContextSnapshot {
application: Some("Brave Browser".into()),
browser_url: Some(Url::parse("https://x.com/home").unwrap()),
..ContextSnapshot::default()
};
let calls = Arc::new(AtomicUsize::new(0));
let capture_calls = calls.clone();
let expected = captured.clone();
let monitor = ContextMonitor::start_with_capture(
move || {
if capture_calls.fetch_add(1, Ordering::Relaxed) == 0 {
Ok(captured.clone())
} else {
Err(eyre!("browser adapter failed"))
}
},
Duration::from_millis(1),
);
assert_eq!(
monitor
.updates
.recv_timeout(Duration::from_secs(1))
.unwrap(),
expected
);
assert_eq!(
monitor
.updates
.recv_timeout(Duration::from_secs(1))
.unwrap(),
ContextSnapshot::default()
);
}
}