Skip to content

An agentic browser harness: an AI side panel & orb in your own logged-in Chrome, Edge, Arc, Brave or even Firefox run by the agent/subscription you already use (Claude Code, Codex, Antigravity). Free, open source, no API key. Also an MCP server.

feat(windows): the app approves browsers in ask mode, in step with the Mac app: a dialog with the browser, its store, its version and a name field, a tray item and dot, and a toast whose browsentic:// buttons act only with their request's nonce, from Action Center or with the app closed; Settings choose automatic, ask or code; the Browsers view says how each paired, renames it, and lists the ones kept out with Reconnect

Shahriar4f7a18b4c91f
diff --git a/docs/internals/windows-app.md b/docs/internals/windows-app.md
index ad7d3a3..24b6e44 100644
--- a/docs/internals/windows-app.md
+++ b/docs/internals/windows-app.md
@@ -100,9 +100,25 @@ and sets it up without a press, as `finishUpdateOnLaunch` does on macOS.
The installer is NSIS, per user, into `%LOCALAPPDATA%\Browsentic`.
[installer-hooks.nsh](../../src/windows/src-tauri/installer-hooks.nsh) runs `Browsentic.exe
---uninstall` before a real uninstall, which stops the daemon and takes `bin` off the `PATH`; an update
+--uninstall` before a real uninstall, which unregisters the browsers' native host, stops the daemon and
+takes `bin` off the `PATH`; an update
also runs the old uninstaller, with `/UPDATE`, and the hook skips it then.
+## Approving a browser
+
+The app watches `pairRequests` on every control socket, so it is the approver the Bridge names while
+it runs. A browser asking to pair in ask mode shows as a dialog in the window (oldest first, with a
+name field), a tray item and a dot on the tray icon, and a toast when the window does not have
+focus. The toast is built in Rust (`pairing.rs`) and posted under the AUMID the NSIS installer puts
+on the Start-menu shortcut, `com.imshaikot.browsentic`. Its buttons are `browsentic://pair/…` links:
+the `deep-link` plugin registers the scheme and the single-instance plugin hands a link to the
+running copy, so a button works from Action Center and with the app closed. Any web page can open
+such a link, so `Held::act` lets one decide or unpair only with the exact nonce the app holds for
+that request (the Bridge's) or session (the app's own); anything else just opens the window. Links
+that start the app wait for the first pending list, at most eight. When no app is watching, the
+Bridge starts it with `--pairing`, which re-subscribes a running copy without showing its window.
+The NSIS uninstall hook runs `browsentic unregister-host` before `stop`.
+
## Build and test
```powershell
diff --git a/src/windows/Cargo.lock b/src/windows/Cargo.lock
index 427270a..63d520c 100644
--- a/src/windows/Cargo.lock
+++ b/src/windows/Cargo.lock
@@ -327,12 +327,14 @@ name = "browsentic-desktop"
version = "0.0.0"
dependencies = [
"futures-util",
+ "getrandom 0.3.4",
"reqwest 0.12.28",
"serde",
"serde_json",
"sha2",
"tauri",
"tauri-build",
+ "tauri-plugin-deep-link",
"tauri-plugin-opener",
"tauri-plugin-single-instance",
"tauri-plugin-updater",
@@ -340,6 +342,8 @@ dependencies = [
"time",
"tokio",
"tokio-tungstenite",
+ "url",
+ "windows 0.62.2",
"windows-sys 0.61.2",
"winreg 0.56.0",
"zip",
@@ -565,6 +569,26 @@ version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c"
+[[package]]
+name = "const-random"
+version = "0.1.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "87e00182fe74b066627d63b85fd550ac2998d4b0bd86bfed477a0ae4c7c71359"
+dependencies = [
+ "const-random-macro",
+]
+
+[[package]]
+name = "const-random-macro"
+version = "0.1.16"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f9d839f2a20b0aee515dc581a6172f2321f96cab76c1a38a4c584a194955390e"
+dependencies = [
+ "getrandom 0.2.17",
+ "once_cell",
+ "tiny-keccak",
+]
+
[[package]]
name = "cookie"
version = "0.18.2"
@@ -657,6 +681,12 @@ version = "0.8.23"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"
+[[package]]
+name = "crunchy"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
+
[[package]]
name = "crypto-common"
version = "0.1.7"
@@ -914,6 +944,15 @@ dependencies = [
"syn 2.0.119",
]
+[[package]]
+name = "dlv-list"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "442039f5147480ba31067cb00ada1adae6892028e40e45fc5de7b7df6dcc1b5f"
+dependencies = [
+ "const-random",
+]
+
[[package]]
name = "dom_query"
version = "0.28.0"
@@ -1367,6 +1406,17 @@ dependencies = [
"version_check",
]
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "wasi",
+]
+
[[package]]
name = "getrandom"
version = "0.3.4"
@@ -1545,6 +1595,12 @@ version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"
+[[package]]
+name = "hashbrown"
+version = "0.14.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1"
+
[[package]]
name = "hashbrown"
version = "0.17.1"
@@ -2636,6 +2692,16 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d"
+[[package]]
+name = "ordered-multimap"
+version = "0.7.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "49203cdcae0030493bad186b28da2fa25645fa276a51b6fec8010d281e02ef79"
+dependencies = [
+ "dlv-list",
+ "hashbrown 0.14.5",
+]
+
[[package]]
name = "ordered-stream"
version = "0.2.0"
@@ -3148,6 +3214,16 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "rust-ini"
+version = "0.21.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "796e8d2b6696392a43bea58116b667fb4c29727dc5abd27d6acf338bb4f688c7"
+dependencies = [
+ "cfg-if",
+ "ordered-multimap",
+]
+
[[package]]
name = "rustc-hash"
version = "2.1.3"
@@ -3653,9 +3729,9 @@ checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
[[package]]
name = "swift-rs"
-version = "1.0.8"
+version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e45c444e496845d3f2a351146bff59aae4975b2280238df1dfaa0c7d1846f38e"
+checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9"
dependencies = [
"base64 0.21.7",
"serde",
@@ -3911,9 +3987,9 @@ dependencies = [
[[package]]
name = "tauri-plugin"
-version = "2.7.0"
+version = "2.7.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c9ff3ebb9fda56ceb93d46f6cbb126bae82951bf43498543a5163dde5def49a1"
+checksum = "67fb21a77e8f94e8beb3325e583102488659365af0a3948b7ea244c5b779c291"
dependencies = [
"anyhow",
"glob",
@@ -3925,6 +4001,27 @@ dependencies = [
"walkdir",
]
+[[package]]
+name = "tauri-plugin-deep-link"
+version = "2.6.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b3c64e24ebcbc63aaa2d88a9c51e2507084b46620baf39ecb0baa0738a08bb4"
+dependencies = [
+ "dunce",
+ "plist",
+ "rust-ini",
+ "serde",
+ "serde_json",
+ "tauri",
+ "tauri-plugin",
+ "tauri-utils",
+ "thiserror 2.0.21",
+ "tracing",
+ "url",
+ "windows-registry",
+ "windows-result 0.4.1",
+]
+
[[package]]
name = "tauri-plugin-opener"
version = "2.5.5"
@@ -3956,6 +4053,7 @@ dependencies = [
"serde",
"serde_json",
"tauri",
+ "tauri-plugin-deep-link",
"thiserror 2.0.21",
"tokio",
"tracing",
@@ -4047,9 +4145,9 @@ dependencies = [
[[package]]
name = "tauri-utils"
-version = "2.10.0"
+version = "2.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4dd257082deff79550de3409ed146104aeaf86fe38649615b04a304144939677"
+checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3"
dependencies = [
"anyhow",
"brotli",
@@ -4186,6 +4284,15 @@ dependencies = [
"time-core",
]
+[[package]]
+name = "tiny-keccak"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2c9d3793400a45f954c52e73d068316d76b6f4e36977e3fcebb13a2721e80237"
+dependencies = [
+ "crunchy",
+]
+
[[package]]
name = "tinystr"
version = "0.8.4"
@@ -5007,6 +5114,17 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "windows-registry"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "02752bf7fbdcce7f2a27a742f798510f3e5ad88dbe84871e5168e2120c3d5720"
+dependencies = [
+ "windows-link 0.2.1",
+ "windows-result 0.4.1",
+ "windows-strings 0.5.1",
+]
+
[[package]]
name = "windows-result"
version = "0.3.4"
diff --git a/src/windows/src-tauri/Cargo.toml b/src/windows/src-tauri/Cargo.toml
index 8a7dda1..feb1fe0 100644
--- a/src/windows/src-tauri/Cargo.toml
+++ b/src/windows/src-tauri/Cargo.toml
@@ -13,20 +13,24 @@ tauri-build = { version = "2", features = [] }
[dependencies]
futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] }
+getrandom = "0.3"
reqwest = { version = "0.12", default-features = false, features = ["json", "native-tls"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
sha2 = "0.10"
tauri = { version = "~2.12", features = ["tray-icon", "image-png"] }
+tauri-plugin-deep-link = "~2.6"
tauri-plugin-opener = "~2.5"
-tauri-plugin-single-instance = "2"
+tauri-plugin-single-instance = { version = "2", features = ["deep-link"] }
tauri-plugin-updater = { version = "~2.12", default-features = false, features = ["native-tls"] }
time = { version = "0.3", features = ["formatting"] }
tokio = { version = "1", features = ["fs", "io-util", "macros", "net", "process", "rt", "sync", "time"] }
tokio-tungstenite = "0.30"
+url = "2"
zip = { version = "8", default-features = false, features = ["deflate"] }
[target.'cfg(windows)'.dependencies]
+windows = { version = "0.62", features = ["Data_Xml_Dom", "UI_Notifications"] }
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_System_Environment", "Win32_UI_WindowsAndMessaging"] }
winreg = "0.56"
diff --git a/src/windows/src-tauri/src/main.rs b/src/windows/src-tauri/src/main.rs
index 2333e36..8ef0fc3 100644
--- a/src/windows/src-tauri/src/main.rs
+++ b/src/windows/src-tauri/src/main.rs
@@ -2,6 +2,7 @@
mod control;
mod node;
+mod pairing;
mod path_env;
mod paths;
mod payload;
@@ -16,6 +17,7 @@ use std::io::{Read, Seek, SeekFrom};
use std::path::PathBuf;
use std::time::Duration;
use tauri::{AppHandle, Emitter, Manager, State, WindowEvent};
+use tauri_plugin_deep_link::DeepLinkExt;
use tokio::sync::Mutex;
use node::NodeInstall;
@@ -30,6 +32,9 @@ type Result<T> = std::result::Result<T, String>;
const LOG_TAIL: u64 = 96_000;
+/// How Browsentic Bridge starts the app when a browser asks to pair and no app is watching.
+const PAIRING_LAUNCH: &str = "--pairing";
+
fn bundle(app: &AppHandle) -> Option<payload::Bundle> {
let resources = app.path().resource_dir().ok()?;
let bundle = payload::Bundle {
@@ -187,6 +192,64 @@ fn tray_status(tray: State<'_, tray::Tray>, status: tray::Status) -> Result<()>
tray.apply(&status).map_err(|error| error.to_string())
}
+/// Mirrors the Bridge's pending list: a toast for each new request while the window is out of sight,
+/// the toasts of decided ones taken back, and any link that was waiting for the list judged now.
+#[tauri::command]
+fn pair_requests(app: AppHandle, held: State<'_, pairing::Pairing>, requests: Vec<pairing::Request>) -> Result<()> {
+ let change = held.list(&requests);
+ let app_id = &app.config().identifier;
+ if !focused(&app) {
+ for request in &change.added {
+ pairing::post(app_id, &pairing::request_toast(request), Some(&request.id));
+ }
+ }
+ for id in &change.removed {
+ pairing::withdraw(app_id, id);
+ }
+ for act in change.released {
+ perform(&app, act);
+ }
+ Ok(())
+}
+
+#[tauri::command]
+fn announce_paired(app: AppHandle, held: State<'_, pairing::Pairing>, session: String, name: String) -> Result<()> {
+ let nonce = held.vouch_for(&session)?;
+ if !focused(&app) {
+ pairing::post(&app.config().identifier, &pairing::paired_toast(&session, &name, &nonce), None);
+ }
+ Ok(())
+}
+
+fn focused(app: &AppHandle) -> bool {
+ app.get_webview_window("main").and_then(|window| window.is_focused().ok()).unwrap_or(false)
+}
+
+fn follow(app: &AppHandle, address: &str) {
+ match pairing::parse(address).and_then(|link| app.state::<pairing::Pairing>().judge(link)) {
+ Some(act) => perform(app, act),
+ None => tray::show(app),
+ }
+}
+
+fn perform(app: &AppHandle, act: pairing::Act) {
+ if act.opens_window() {
+ tray::show(app);
+ }
+ let _ = app.emit("pair-link", act);
+}
+
+/// A second copy hands its arguments here: a link was already followed, and a start for pairing only
+/// makes sure the window is watching, without taking the keyboard from the browser that asked.
+fn second_launch(app: &AppHandle, args: Vec<String>) {
+ let scheme = format!("{}:", pairing::SCHEME);
+ if args.iter().any(|arg| arg == PAIRING_LAUNCH) {
+ let _ = app.emit("pairing-launch", ());
+ } else if !args.iter().any(|arg| arg.to_ascii_lowercase().starts_with(&scheme)) {
+ tray::show(app);
+ }
+}
+
#[tauri::command]
async fn check_update(app: AppHandle) -> Result<Option<update::Release>> {
update::check(&app).await
@@ -218,13 +281,20 @@ fn main() {
return prepare_uninstall();
}
tauri::Builder::default()
- .plugin(tauri_plugin_single_instance::init(|app, _, _| tray::show(app)))
+ .plugin(tauri_plugin_single_instance::init(|app, args, _| second_launch(app, args)))
+ .plugin(tauri_plugin_deep_link::init())
.plugin(tauri_plugin_opener::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.manage(App { paths: paths::Paths::from_env(), control: control::Control::default(), node: Mutex::default() })
+ .manage(pairing::Pairing::default())
.setup(|app| {
let tray = tray::build(app.handle())?;
app.manage(tray);
+ let handle = app.handle().clone();
+ app.deep_link().on_open_url(move |event| event.urls().iter().for_each(|url| follow(&handle, url.as_str())));
+ for url in app.deep_link().get_current().ok().flatten().unwrap_or_default() {
+ follow(app.handle(), url.as_str());
+ }
Ok(())
})
.on_window_event(|window, event| {
@@ -235,6 +305,7 @@ fn main() {
})
.invoke_handler(tauri::generate_handler![
agents_on_path,
+ announce_paired,
app_info,
browsers,
check_update,
@@ -251,6 +322,7 @@ fn main() {
log_tail,
npm_install,
open_extensions_page,
+ pair_requests,
read_lock,
set_command_link,
tray_status,
diff --git a/src/windows/src-tauri/src/pairing.rs b/src/windows/src-tauri/src/pairing.rs
new file mode 100644
index 0000000..a703782
--- /dev/null
+++ b/src/windows/src-tauri/src/pairing.rs
@@ -0,0 +1,329 @@
+use serde::{Deserialize, Serialize};
+use std::collections::HashMap;
+use std::sync::Mutex;
+use url::Url;
+
+/// Registered by the installer, so a toast's buttons reach this app whether it is running or not.
+pub const SCHEME: &str = "browsentic";
+
+/// What a `browsentic://pair/…` link asks for. Any web page can open one, so none of this is trusted
+/// until [`Held::act`] has matched its nonce.
+#[derive(Debug, Clone, PartialEq)]
+pub enum Link {
+ Decide { request: String, nonce: String, allow: bool },
+ Unpair { session: String, nonce: String },
+ Open { request: Option<String> },
+}
+
+pub fn parse(address: &str) -> Option<Link> {
+ let url = Url::parse(address).ok()?;
+ if url.scheme() != SCHEME || url.host_str() != Some("pair") {
+ return None;
+ }
+ let query: HashMap<String, String> = url.query_pairs().into_owned().collect();
+ let take = |key: &str| query.get(key).filter(|value| !value.is_empty()).cloned();
+ let nonce = take("n").unwrap_or_default();
+ match url.path().trim_end_matches('/') {
+ "/allow" => Some(Link::Decide { request: take("r")?, nonce, allow: true }),
+ "/deny" => Some(Link::Decide { request: take("r")?, nonce, allow: false }),
+ "/unpair" => Some(Link::Unpair { session: take("s")?, nonce }),
+ "/open" => Some(Link::Open { request: take("r") }),
+ _ => None,
+ }
+}
+
+/// What the window does with a link once it has been judged.
+#[derive(Debug, Clone, PartialEq, Serialize)]
+#[serde(tag = "kind", rename_all = "camelCase")]
+pub enum Act {
+ Decide { request: String, allow: bool },
+ Unpair { session: String },
+ Show { request: Option<String> },
+ Browsers,
+}
+
+impl Act {
+ pub fn opens_window(&self) -> bool {
+ matches!(self, Act::Show { .. } | Act::Browsers)
+ }
+}
+
+/// A pending request as the Bridge lists it; the nonce reached only approvers such as this app.
+#[derive(Deserialize, Clone, Debug, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Request {
+ pub id: String,
+ pub browser: Option<String>,
+ pub nonce: String,
+}
+
+/// The nonces this app can vouch for: the Bridge's for each pending request, and its own for each
+/// browser it announced as paired by itself.
+#[derive(Default)]
+pub struct Held {
+ requests: Option<HashMap<String, String>>,
+ sessions: HashMap<String, String>,
+}
+
+impl Held {
+ /// A link decides or unpairs only with the nonce held for it; any other link just opens the window.
+ /// None until the pending list has been read, so a link that started the app waits for it.
+ pub fn act(&self, link: &Link) -> Option<Act> {
+ Some(match link {
+ Link::Decide { request, nonce, allow } => match &self.requests {
+ None => return None,
+ Some(requests) if same_secret(requests.get(request), nonce) => Act::Decide { request: request.clone(), allow: *allow },
+ Some(_) => Act::Show { request: Some(request.clone()) },
+ },
+ Link::Unpair { session, nonce } if same_secret(self.sessions.get(session), nonce) => Act::Unpair { session: session.clone() },
+ Link::Unpair { .. } => Act::Browsers,
+ Link::Open { request } => Act::Show { request: request.clone() },
+ })
+ }
+}
+
+fn same_secret(held: Option<&String>, offered: &str) -> bool {
+ held.is_some_and(|held| {
+ !held.is_empty() && held.len() == offered.len() && held.bytes().zip(offered.bytes()).fold(0, |differs, (a, b)| differs | (a ^ b)) == 0
+ })
+}
+
+/// What changed since the last list: toasts to post and to take back, and links that were waiting for it.
+#[derive(Debug, Default, PartialEq)]
+pub struct Change {
+ pub added: Vec<Request>,
+ pub removed: Vec<String>,
+ pub released: Vec<Act>,
+}
+
+/// Links that arrive before the pending list are kept for it, but only a few: any web page can send them.
+const MOST_WAITING: usize = 8;
+
+#[derive(Default)]
+pub struct Pairing {
+ held: Mutex<Held>,
+ waiting: Mutex<Vec<Link>>,
+}
+
+impl Pairing {
+ pub fn list(&self, requests: &[Request]) -> Change {
+ let mut held = self.held.lock().unwrap();
+ let before = held.requests.take().unwrap_or_default();
+ let now: HashMap<String, String> = requests.iter().map(|request| (request.id.clone(), request.nonce.clone())).collect();
+ let added = requests.iter().filter(|request| !before.contains_key(&request.id)).cloned().collect();
+ let removed = before.keys().filter(|id| !now.contains_key(*id)).cloned().collect();
+ held.requests = Some(now);
+ let released = self.waiting.lock().unwrap().drain(..).filter_map(|link| held.act(&link)).collect();
+ Change { added, removed, released }
+ }
+
+ /// None when the link has to wait for the pending list.
+ pub fn judge(&self, link: Link) -> Option<Act> {
+ let act = self.held.lock().unwrap().act(&link);
+ let mut waiting = self.waiting.lock().unwrap();
+ if act.is_none() && waiting.len() < MOST_WAITING {
+ waiting.push(link);
+ }
+ act
+ }
+
+ pub fn vouch_for(&self, session: &str) -> Result<String, String> {
+ let nonce = mint()?;
+ self.held.lock().unwrap().sessions.insert(session.to_string(), nonce.clone());
+ Ok(nonce)
+ }
+}
+
+fn mint() -> Result<String, String> {
+ let mut bytes = [0u8; 16];
+ getrandom::fill(&mut bytes).map_err(|_| "Windows gave no random numbers to secure the notification with.".to_string())?;
+ Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
+}
+
+fn link(path: &str, query: &[(&str, &str)]) -> String {
+ let mut address = Url::parse(&format!("{SCHEME}://pair/{path}")).expect("a pair link is a valid address");
+ if !query.is_empty() {
+ address.query_pairs_mut().extend_pairs(query);
+ }
+ address.into()
+}
+
+fn escape(text: &str) -> String {
+ text.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
+}
+
+fn toast(launch: &str, title: &str, body: &str, buttons: &[(&str, String)]) -> String {
+ let actions: String = buttons
+ .iter()
+ .map(|(label, target)| format!(r#"<action content="{}" activationType="protocol" arguments="{}"/>"#, escape(label), escape(target)))
+ .collect();
+ format!(
+ r#"<toast launch="{}" activationType="protocol" duration="long"><visual><binding template="ToastGeneric"><text>{}</text><text>{}</text></binding></visual><actions>{actions}</actions></toast>"#,
+ escape(launch),
+ escape(title),
+ escape(body),
+ )
+}
+
+pub fn request_toast(request: &Request) -> String {
+ let browser = request.browser.as_deref().unwrap_or("A browser");
+ let there = request.browser.as_deref().unwrap_or("this browser");
+ let decide = |path: &str| link(path, &[("r", &request.id), ("n", &request.nonce)]);
+ toast(
+ &link("open", &[("r", &request.id)]),
+ &format!("{browser} wants to connect to Browsentic Bridge"),
+ &format!("Allow it to use your agent and drive this browser? If you didn’t just install or open Browsentic in {there}, don’t allow it."),
+ &[("Allow", decide("allow")), ("Deny", decide("deny"))],
+ )
+}
+
+pub fn paired_toast(session: &str, name: &str, nonce: &str) -> String {
+ toast(
+ &link("open", &[]),
+ &format!("{name} connected to Browsentic Bridge"),
+ &format!("It paired by itself. If you didn’t just install or open Browsentic in {name}, unpair it."),
+ &[("Unpair", link("unpair", &[("s", session), ("n", nonce)]))],
+ )
+}
+
+#[cfg(windows)]
+mod toasts {
+ use windows::core::HSTRING;
+ use windows::Data::Xml::Dom::XmlDocument;
+ use windows::UI::Notifications::{ToastNotification, ToastNotificationManager};
+
+ const GROUP: &str = "pair";
+
+ pub fn post(app_id: &str, xml: &str, tag: Option<&str>) -> windows::core::Result<()> {
+ let content = XmlDocument::new()?;
+ content.LoadXml(&HSTRING::from(xml))?;
+ let toast = ToastNotification::CreateToastNotification(&content)?;
+ if let Some(tag) = tag {
+ toast.SetTag(&HSTRING::from(tag))?;
+ toast.SetGroup(&HSTRING::from(GROUP))?;
+ }
+ ToastNotificationManager::CreateToastNotifierWithId(&HSTRING::from(app_id))?.Show(&toast)
+ }
+
+ pub fn withdraw(app_id: &str, tag: &str) -> windows::core::Result<()> {
+ ToastNotificationManager::History()?.RemoveGroupedTagWithId(&HSTRING::from(tag), &HSTRING::from(GROUP), &HSTRING::from(app_id))
+ }
+}
+
+/// Toasts go to the identity the installer stamps on the Start menu shortcut; without that shortcut, as
+/// in a development build, Windows drops them and the tray item and the window carry the request alone.
+#[cfg(windows)]
+pub fn post(app_id: &str, xml: &str, tag: Option<&str>) {
+ let _ = toasts::post(app_id, xml, tag);
+}
+
+#[cfg(windows)]
+pub fn withdraw(app_id: &str, tag: &str) {
+ let _ = toasts::withdraw(app_id, tag);
+}
+
+#[cfg(not(windows))]
+pub fn post(_: &str, _: &str, _: Option<&str>) {}
+
+#[cfg(not(windows))]
+pub fn withdraw(_: &str, _: &str) {}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn request(id: &str, nonce: &str) -> Request {
+ Request { id: id.into(), browser: Some("Brave".into()), nonce: nonce.into() }
+ }
+
+ #[test]
+ fn reads_each_link_the_toasts_carry_and_nothing_else() {
+ assert_eq!(parse("browsentic://pair/allow?r=Ab3_x-9q&n=NONCE"), Some(Link::Decide { request: "Ab3_x-9q".into(), nonce: "NONCE".into(), allow: true }));
+ assert_eq!(parse("browsentic://pair/deny/?r=Ab3&n=N"), Some(Link::Decide { request: "Ab3".into(), nonce: "N".into(), allow: false }));
+ assert_eq!(parse("browsentic://pair/unpair?s=chrome-extension%3A%2F%2Fabc%2F&n=N"), Some(Link::Unpair { session: "chrome-extension://abc/".into(), nonce: "N".into() }));
+ assert_eq!(parse("browsentic://pair/open?r=Ab3"), Some(Link::Open { request: Some("Ab3".into()) }));
+ assert_eq!(parse("browsentic://pair/open"), Some(Link::Open { request: None }));
+ assert_eq!(parse("browsentic://pair/allow?r=Ab3"), Some(Link::Decide { request: "Ab3".into(), nonce: String::new(), allow: true }));
+ assert_eq!(parse("browsentic://pair/allow?n=N"), None);
+ assert_eq!(parse("browsentic://elsewhere/allow?r=Ab3&n=N"), None);
+ assert_eq!(parse("https://pair/allow?r=Ab3&n=N"), None);
+ assert_eq!(parse("--pairing"), None);
+ assert_eq!(parse("browsentic://pair/approve-all"), None);
+ }
+
+ #[test]
+ fn a_link_acts_only_with_the_nonce_held_for_it_and_otherwise_opens_the_window() {
+ let pairing = Pairing::default();
+ pairing.list(&[request("r1", "secret-one")]);
+ let session_nonce = pairing.vouch_for("s1").unwrap();
+ let judged = |address: &str| pairing.judge(parse(address).unwrap());
+
+ assert_eq!(judged("browsentic://pair/allow?r=r1&n=secret-one"), Some(Act::Decide { request: "r1".into(), allow: true }));
+ assert_eq!(judged("browsentic://pair/deny?r=r1&n=secret-one"), Some(Act::Decide { request: "r1".into(), allow: false }));
+ assert_eq!(judged("browsentic://pair/allow?r=r1&n=secret-onf"), Some(Act::Show { request: Some("r1".into()) }));
+ assert_eq!(judged("browsentic://pair/allow?r=r1&n=secret"), Some(Act::Show { request: Some("r1".into()) }));
+ assert_eq!(judged("browsentic://pair/allow?r=r1"), Some(Act::Show { request: Some("r1".into()) }));
+ assert_eq!(judged("browsentic://pair/allow?r=r2&n=secret-one"), Some(Act::Show { request: Some("r2".into()) }));
+ assert_eq!(judged(&format!("browsentic://pair/unpair?s=s1&n={session_nonce}")), Some(Act::Unpair { session: "s1".into() }));
+ assert_eq!(judged(&format!("browsentic://pair/unpair?s=s2&n={session_nonce}")), Some(Act::Browsers));
+ assert_eq!(judged("browsentic://pair/unpair?s=s1&n=guess"), Some(Act::Browsers));
+ assert!(!Act::Decide { request: "r1".into(), allow: true }.opens_window());
+ assert!(Act::Browsers.opens_window());
+ }
+
+ #[test]
+ fn a_decided_request_stops_answering_to_its_old_nonce() {
+ let pairing = Pairing::default();
+ pairing.list(&[request("r1", "secret-one")]);
+ let change = pairing.list(&[]);
+ assert_eq!(change.removed, ["r1"]);
+ assert_eq!(pairing.judge(parse("browsentic://pair/allow?r=r1&n=secret-one").unwrap()), Some(Act::Show { request: Some("r1".into()) }));
+ }
+
+ #[test]
+ fn a_link_that_started_the_app_waits_for_the_list_and_is_then_judged_by_it() {
+ let pairing = Pairing::default();
+ assert_eq!(pairing.judge(parse("browsentic://pair/allow?r=r1&n=secret-one").unwrap()), None);
+ assert_eq!(pairing.judge(parse("browsentic://pair/deny?r=r1&n=forged").unwrap()), None);
+ let change = pairing.list(&[request("r1", "secret-one"), request("r2", "secret-two")]);
+ assert_eq!(change.added, [request("r1", "secret-one"), request("r2", "secret-two")]);
+ assert_eq!(change.released, [Act::Decide { request: "r1".into(), allow: true }, Act::Show { request: Some("r1".into()) }]);
+ assert_eq!(pairing.list(&[request("r2", "secret-two")]), Change { added: vec![], removed: vec!["r1".into()], released: vec![] });
+ }
+
+ #[test]
+ fn a_flood_of_links_before_the_list_keeps_only_a_few() {
+ let pairing = Pairing::default();
+ for guess in 0..50 {
+ pairing.judge(parse(&format!("browsentic://pair/allow?r=r1&n={guess}")).unwrap());
+ }
+ assert_eq!(pairing.list(&[request("r1", "secret-one")]).released.len(), MOST_WAITING);
+ }
+
+ #[test]
+ fn each_session_gets_a_fresh_unguessable_nonce() {
+ let pairing = Pairing::default();
+ let (first, second) = (pairing.vouch_for("s1").unwrap(), pairing.vouch_for("s2").unwrap());
+ assert_eq!(first.len(), 32);
+ assert_ne!(first, second);
+ }
+
+ #[test]
+ fn the_toast_carries_the_nonce_only_in_its_buttons_and_escapes_what_the_browser_sent() {
+ let xml = request_toast(&Request { id: "r1".into(), browser: Some("Brave <beta> & co".into()), nonce: "a+b/c".into() });
+ assert!(xml.contains("<text>Brave &lt;beta&gt; &amp; co wants to connect to Browsentic Bridge</text>"));
+ assert!(xml.contains(r#"launch="browsentic://pair/open?r=r1""#));
+ assert!(xml.contains(r#"<action content="Allow" activationType="protocol" arguments="browsentic://pair/allow?r=r1&amp;n=a%2Bb%2Fc"/>"#));
+ assert!(xml.contains(r#"<action content="Deny" activationType="protocol" arguments="browsentic://pair/deny?r=r1&amp;n=a%2Bb%2Fc"/>"#));
+ assert_eq!(parse("browsentic://pair/allow?r=r1&n=a%2Bb%2Fc"), Some(Link::Decide { request: "r1".into(), nonce: "a+b/c".into(), allow: true }));
+
+ let nameless = request_toast(&Request { id: "r1".into(), browser: None, nonce: "n".into() });
+ assert!(nameless.contains("<text>A browser wants to connect to Browsentic Bridge</text>"));
+ assert!(nameless.contains("open Browsentic in this browser, don’t allow it"));
+
+ let paired = paired_toast("chrome-extension://abc/", "Chrome", "n0nce");
+ assert!(paired.contains("<text>Chrome connected to Browsentic Bridge</text>"));
+ assert!(paired.contains(r#"launch="browsentic://pair/open""#));
+ assert!(paired.contains(r#"arguments="browsentic://pair/unpair?s=chrome-extension%3A%2F%2Fabc%2F&amp;n=n0nce""#));
+ }
+}
diff --git a/src/windows/src-tauri/src/tray.rs b/src/windows/src-tauri/src/tray.rs
index 28b5079..f193283 100644
--- a/src/windows/src-tauri/src/tray.rs
+++ b/src/windows/src-tauri/src/tray.rs
@@ -1,12 +1,18 @@
use serde::Deserialize;
+use tauri::image::Image;
use tauri::menu::{Menu, MenuItem, PredefinedMenuItem};
-use tauri::tray::{MouseButton, MouseButtonState, TrayIconBuilder, TrayIconEvent};
+use tauri::tray::{MouseButton, MouseButtonState, TrayIcon, TrayIconBuilder, TrayIconEvent};
use tauri::{AppHandle, Emitter, Manager, Wry};
-/// The menu-bar extra of the macOS app, as a notification-area icon: the daemon's state, turning it
-/// on or off, restarting it, and the window. Closing the window leaves this running.
+/// The menu-bar extra of the macOS app, as a notification-area icon: the daemon's state, a browser
+/// waiting to be let in, turning it on or off, restarting it, and the window. Closing the window
+/// leaves this running.
pub struct Tray {
+ icon: TrayIcon<Wry>,
+ plain: Option<Image<'static>>,
+ dotted: Option<Image<'static>>,
status: MenuItem<Wry>,
+ request: MenuItem<Wry>,
toggle: MenuItem<Wry>,
restart: MenuItem<Wry>,
}
@@ -18,17 +24,22 @@ pub struct Status {
pub toggle: String,
pub can_toggle: bool,
pub can_restart: bool,
+ pub waiting: Option<String>,
}
+const NOBODY_WAITING: &str = "No browser waiting";
+
pub fn build(app: &AppHandle) -> tauri::Result<Tray> {
let item = |id: &str, text: &str, enabled: bool| MenuItem::with_id(app, id, text, enabled, None::<&str>);
let status = item("status", "Daemon: Off", false)?;
+ let request = item("request", NOBODY_WAITING, false)?;
let toggle = item("toggle", "Turn On", false)?;
let restart = item("restart", "Restart", false)?;
let menu = Menu::with_items(
app,
&[
&status,
+ &request,
&PredefinedMenuItem::separator(app)?,
&toggle,
&restart,
@@ -38,36 +49,64 @@ pub fn build(app: &AppHandle) -> tauri::Result<Tray> {
],
)?;
+ let plain = app.default_window_icon().map(|icon| icon.clone().to_owned());
+ let dotted = plain.as_ref().map(|icon| Image::new_owned(with_dot(icon.rgba(), icon.width(), icon.height()), icon.width(), icon.height()));
let mut tray = TrayIconBuilder::with_id("browsentic").tooltip("Browsentic").menu(&menu).show_menu_on_left_click(false);
- if let Some(icon) = app.default_window_icon() {
+ if let Some(icon) = &plain {
tray = tray.icon(icon.clone());
}
- tray.on_menu_event(|app, event| match event.id().as_ref() {
- "open" => show(app),
- "quit" => app.exit(0),
- action => {
- let _ = app.emit("tray", action);
- }
- })
- .on_tray_icon_event(|tray, event| {
- if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event {
- show(tray.app_handle());
- }
- })
- .build(app)?;
+ let icon = tray
+ .on_menu_event(|app, event| match event.id().as_ref() {
+ "open" | "request" => show(app),
+ "quit" => app.exit(0),
+ action => {
+ let _ = app.emit("tray", action);
+ }
+ })
+ .on_tray_icon_event(|tray, event| {
+ if let TrayIconEvent::Click { button: MouseButton::Left, button_state: MouseButtonState::Up, .. } = event {
+ show(tray.app_handle());
+ }
+ })
+ .build(app)?;
- Ok(Tray { status, toggle, restart })
+ Ok(Tray { icon, plain, dotted, status, request, toggle, restart })
}
impl Tray {
pub fn apply(&self, status: &Status) -> tauri::Result<()> {
self.status.set_text(&status.summary)?;
+ self.request.set_text(status.waiting.as_deref().unwrap_or(NOBODY_WAITING))?;
+ self.request.set_enabled(status.waiting.is_some())?;
+ self.icon.set_tooltip(Some(status.waiting.as_deref().map_or("Browsentic".to_string(), |waiting| format!("Browsentic: {waiting}"))))?;
+ self.icon.set_icon(if status.waiting.is_some() { self.dotted.clone() } else { self.plain.clone() })?;
self.toggle.set_text(&status.toggle)?;
self.toggle.set_enabled(status.can_toggle)?;
self.restart.set_enabled(status.can_restart)
}
}
+const DOT: [u8; 4] = [0xF2, 0x7A, 0x3C, 0xFF];
+
+/// The icon with an ember dot in its top-right corner, ringed in transparency so it reads on any taskbar.
+pub fn with_dot(rgba: &[u8], width: u32, height: u32) -> Vec<u8> {
+ let mut pixels = rgba.to_vec();
+ let radius = width.min(height) as f32 * 0.22;
+ let (cx, cy) = (width as f32 - radius - 0.5, radius + 0.5);
+ for y in 0..height {
+ for x in 0..width {
+ let distance = ((x as f32 - cx).powi(2) + (y as f32 - cy).powi(2)).sqrt();
+ let at = ((y * width + x) * 4) as usize;
+ if distance <= radius {
+ pixels[at..at + 4].copy_from_slice(&DOT);
+ } else if distance <= radius + width as f32 * 0.06 {
+ pixels[at + 3] = 0;
+ }
+ }
+ }
+ pixels
+}
+
pub fn show(app: &AppHandle) {
if let Some(window) = app.get_webview_window("main") {
let _ = window.unminimize();
@@ -75,3 +114,19 @@ pub fn show(app: &AppHandle) {
let _ = window.set_focus();
}
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_dot_sits_in_the_top_right_corner_and_leaves_the_rest_of_the_icon_alone() {
+ let icon = vec![9u8; 32 * 32 * 4];
+ let dotted = with_dot(&icon, 32, 32);
+ let pixel = |x: usize, y: usize| &dotted[(y * 32 + x) * 4..(y * 32 + x) * 4 + 4];
+ assert_eq!(pixel(25, 6), DOT);
+ assert_eq!(pixel(4, 28), [9, 9, 9, 9]);
+ assert_eq!(pixel(6, 6), [9, 9, 9, 9]);
+ assert_eq!(dotted.len(), icon.len());
+ }
+}
diff --git a/src/windows/src-tauri/tauri.conf.json b/src/windows/src-tauri/tauri.conf.json
index fa68595..0d83b79 100644
--- a/src/windows/src-tauri/tauri.conf.json
+++ b/src/windows/src-tauri/tauri.conf.json
@@ -51,6 +51,9 @@
}
},
"plugins": {
+ "deep-link": {
+ "desktop": { "schemes": ["browsentic"] }
+ },
"updater": {
"pubkey": "dW50cnVzdGVkIGNvbW1lbnQ6IG1pbmlzaWduIHB1YmxpYyBrZXk6IDM0MDRFRkQ2RjcyMUUzNzEKUldSeDR5SDMxdThFTkkxZXVFa0Y1OVhpTTVaTGdIQmdXV0RpMXliclZnRi81QVJFVEl6dDkwSzUK",
"endpoints": ["https://github.com/imshaikot/browsentic/releases/latest/download/latest.json"],
diff --git a/src/windows/ui/app.tsx b/src/windows/ui/app.tsx
index d55244c..8114a71 100644
--- a/src/windows/ui/app.tsx
+++ b/src/windows/ui/app.tsx
@@ -4,6 +4,7 @@ import { Backdrop, NoticeBanner } from './components';
import { TABS, useModelState, type Appearance, type Model } from './model';
import type { Backend } from './backend';
import { MainView } from './views/main';
+import { PairRequestQueue } from './views/pair-request';
import { PreflightView } from './views/preflight';
const darkQuery = () => window.matchMedia('(prefers-color-scheme: dark)');
@@ -67,8 +68,9 @@ export function App({ model, backend }: { model: Model; backend: Backend }) {
<div className="relative h-full">
{state.phase === 'preflight' ? <PreflightView model={model} state={state} /> : <MainView model={model} state={state} />}
</div>
+ <PairRequestQueue model={model} state={state} />
{state.notice && (
- <div key={state.notice.id} className="enter pointer-events-auto fixed inset-x-0 bottom-5.5 flex justify-center px-6">
+ <div key={state.notice.id} className="enter pointer-events-auto fixed inset-x-0 bottom-5.5 z-[60] flex justify-center px-6">
<NoticeBanner text={state.notice.text} isError={state.notice.isError} />
</div>
)}
diff --git a/src/windows/ui/backend.ts b/src/windows/ui/backend.ts
index 7cabc7b..31a0270 100644
--- a/src/windows/ui/backend.ts
+++ b/src/windows/ui/backend.ts
@@ -1,8 +1,9 @@
import type { BridgeStatus, SessionSummary } from '@/daemon/control';
import type { AgentDescriptor, AgentState } from '@/lib/agents/catalog';
+import type { BlockedBrowser, PairRequestSummary, PairedBy, PairingMode } from '@/lib/pairing';
import type { Preferences } from '@/lib/settings/preferences';
-export type { BridgeStatus, SessionSummary };
+export type { BlockedBrowser, BridgeStatus, PairRequestSummary, PairedBy, PairingMode, SessionSummary };
export interface NodeInstall {
path: string;
@@ -68,8 +69,20 @@ export interface TrayStatus {
toggle: string;
canToggle: boolean;
canRestart: boolean;
+ /** The tray item for the first browser waiting to be let in; null when none is. */
+ waiting: string | null;
}
+/**
+ * What a `browsentic://pair/…` link comes to once the Rust side has checked its nonce: a decision or an
+ * unpairing only when the link carried the nonce held for it, and otherwise just the window.
+ */
+export type PairLinkAct =
+ | { kind: 'decide'; request: string; allow: boolean }
+ | { kind: 'unpair'; session: string }
+ | { kind: 'show'; request: string | null }
+ | { kind: 'browsers' };
+
export interface Progress {
fraction: number;
label: string;
@@ -146,10 +159,17 @@ export interface Backend {
controlRequest(frame: Record<string, unknown>, timeoutMs?: number): Promise<Record<string, unknown>>;
controlClose(): Promise<void>;
trayStatus(status: TrayStatus): Promise<void>;
+ /** Hands the Bridge's pending list to the Rust side, which posts and withdraws the toasts and holds their nonces. */
+ pairRequests(requests: PairRequestSummary[]): Promise<void>;
+ /** A toast with an Unpair button, for a browser that paired by itself. */
+ announcePaired(session: string, name: string): Promise<void>;
checkUpdate(): Promise<Release | null>;
installUpdate(onProgress: (fraction: number) => void): Promise<void>;
onControlEvent(listener: (event: string) => void): () => void;
onTray(listener: (action: string) => void): () => void;
+ onPairLink(listener: (act: PairLinkAct) => void): () => void;
+ /** Browsentic Bridge started a second copy because a browser asked to pair and this window was not watching. */
+ onPairingLaunch(listener: () => void): () => void;
openUrl(url: string): Promise<void>;
reveal(path: string): Promise<void>;
setWindowTheme(theme: 'light' | 'dark' | null): Promise<void>;
@@ -189,6 +209,8 @@ export async function tauriBackend(): Promise<Backend> {
controlRequest: (frame, timeoutMs) => invoke('control_request', { frame, timeoutMs }),
controlClose: () => invoke('control_close'),
trayStatus: (status) => invoke('tray_status', { status }),
+ pairRequests: (requests) => invoke('pair_requests', { requests }),
+ announcePaired: (session, name) => invoke('announce_paired', { session, name }),
checkUpdate: () => invoke('check_update'),
installUpdate: async (onProgress) => {
const stop = await listen<{ received: number; total: number | null }>('update-progress', ({ payload }) =>
@@ -202,6 +224,8 @@ export async function tauriBackend(): Promise<Backend> {
},
onControlEvent: (listener) => unlisten(listen<string>('control-event', (event) => listener(event.payload))),
onTray: (listener) => unlisten(listen<string>('tray', (event) => listener(event.payload))),
+ onPairLink: (listener) => unlisten(listen<PairLinkAct>('pair-link', (event) => listener(event.payload))),
+ onPairingLaunch: (listener) => unlisten(listen('pairing-launch', () => listener())),
openUrl: (url) => opener.openUrl(url),
reveal: (path) => opener.revealItemInDir(path),
setWindowTheme: (theme) => getCurrentWindow().setTheme(theme),
diff --git a/src/windows/ui/components.tsx b/src/windows/ui/components.tsx
index b932684..ceab26b 100644
--- a/src/windows/ui/components.tsx
+++ b/src/windows/ui/components.tsx
@@ -240,6 +240,10 @@ export function Segmented<T extends string>({
);
}
+/**
+ * A question the window waits on. A destructive one confirms in red and closes from the backdrop; one
+ * that must be answered, such as a browser asking to connect, passes `dismissible={false}`.
+ */
export function ConfirmDialog({
title,
message,
@@ -247,6 +251,10 @@ export function ConfirmDialog({
onConfirm,
onCancel,
children,
+ tint = 'danger',
+ cancel = 'Cancel',
+ dismissible = true,
+ busy = false,
}: {
title: string;
message: string;
@@ -254,20 +262,56 @@ export function ConfirmDialog({
onConfirm: () => void;
onCancel: () => void;
children?: ReactNode;
+ tint?: 'danger' | 'brand';
+ cancel?: string;
+ dismissible?: boolean;
+ busy?: boolean;
}) {
return (
- <div role="dialog" aria-modal aria-label={title} className="fixed inset-0 z-50 flex items-center justify-center bg-ground/60 backdrop-blur-sm" onClick={onCancel}>
- <div className="enter w-[440px] space-y-3.5 rounded-2xl border border-line-strong bg-ground p-6 shadow-2xl" onClick={(event) => event.stopPropagation()}>
+ <div
+ role="dialog"
+ aria-modal
+ aria-label={title}
+ className="fixed inset-0 z-50 flex items-center justify-center bg-ground/60 backdrop-blur-sm"
+ onClick={dismissible ? onCancel : undefined}
+ >
+ <form
+ className="enter w-[440px] space-y-3.5 rounded-2xl border border-line-strong bg-ground p-6 shadow-2xl"
+ onClick={(event) => event.stopPropagation()}
+ onSubmit={(event) => {
+ event.preventDefault();
+ onConfirm();
+ }}
+ >
<h2 className="font-display text-lg font-semibold text-ink">{title}</h2>
<p className="text-[12.5px] leading-relaxed whitespace-pre-line text-ink-dim">{message}</p>
{children}
<div className="flex justify-end gap-2 pt-1">
- <QuietButton onClick={onCancel}>Cancel</QuietButton>
- <PrimaryButton tint="danger" onClick={onConfirm}>
+ <QuietButton disabled={busy} onClick={onCancel}>
+ {cancel}
+ </QuietButton>
+ <PrimaryButton type="submit" tint={tint} disabled={busy} autoFocus={tint !== 'danger'}>
{action}
</PrimaryButton>
</div>
- </div>
+ </form>
</div>
);
}
+
+export function TextField({ label, value, onChange, placeholder, maxLength }: { label: string; value: string; onChange: (next: string) => void; placeholder?: string; maxLength?: number }) {
+ return (
+ <label className="block space-y-1.5">
+ <span className="text-xs font-medium text-ink-dim">{label}</span>
+ <input
+ type="text"
+ value={value}
+ placeholder={placeholder}
+ maxLength={maxLength}
+ spellCheck={false}
+ onChange={(event) => onChange(event.target.value)}
+ className="w-full rounded-[10px] border border-line bg-ground-2 px-3 py-2 text-[13px] text-ink outline-none placeholder:text-ink-faint focus:border-brand/60"
+ />
+ </label>
+ );
+}
diff --git a/src/windows/ui/mock-backend.ts b/src/windows/ui/mock-backend.ts
index e07e861..0a9ffd9 100644
--- a/src/windows/ui/mock-backend.ts
+++ b/src/windows/ui/mock-backend.ts
@@ -7,14 +7,30 @@ import { AGENT_LIST, AGENTS, type AgentKind } from '@/lib/agents/catalog';
import type { GuardrailSettings } from '@/lib/settings/guardrails';
import type { PreferenceChange } from '@/lib/settings/preferences';
import { EMPTY_PROFILE } from '@/lib/settings/profile';
-import type { AgentListing, Backend, CliOutput, InstallStamp, Lockfile, NodeInstall, Preferences } from './backend';
+import type { Source } from '@/lib/stores';
+import type { AgentListing, Backend, BlockedBrowser, CliOutput, InstallStamp, Lockfile, NodeInstall, PairRequestSummary, PairedBy, PairingMode, Preferences } from './backend';
+
+/**
+ * How the stand-in machine pairs, picked by the address's hash: #ask has two browsers waiting to be
+ * let in, #kept has two kept out, #arrives has Edge pair by itself a moment after the window opens,
+ * and #code pairs only by code. Anything else pairs automatically with nobody waiting.
+ */
+export type Scenario = 'ask' | 'kept' | 'arrives' | 'code' | 'auto';
+const SCENARIOS: Scenario[] = ['ask', 'kept', 'arrives', 'code', 'auto'];
+const scenarioOf = (hash: string): Scenario => SCENARIOS.find((scenario) => `#${scenario}` === hash) ?? 'auto';
+
+/** The stand-in, with the hands a test needs: a browser asking, and one pairing by itself. */
+export interface MockBackend extends Backend {
+ ask(request: PairRequestSummary): void;
+ arrive(): void;
+}
/**
* A stand-in machine for working on the window in a plain browser: `yarn win:preview`. Everything
* is installed and the daemon is running, unless the address ends in #fresh, which starts from a
* computer that has nothing yet.
*/
-export function mockBackend({ instant = false, fresh = location.hash === '#fresh' } = {}): Backend {
+export function mockBackend({ instant = false, fresh = location.hash === '#fresh', scenario = scenarioOf(location.hash) } = {}): MockBackend {
const home = 'C:\\Users\\you';
const version = '0.8.0';
let node: NodeInstall | null = fresh ? null : { path: `${home}\\.browsentic\\runtime\\node\\node.exe`, version: 'v24.11.1', isPrivate: true };
@@ -30,6 +46,13 @@ export function mockBackend({ instant = false, fresh = location.hash === '#fresh
let preferences: Preferences = { theme: null, guardrails: guardrails(`${home}\\.browsentic\\config.json`), profile: EMPTY_PROFILE };
const phones = phoneStates(home);
let phone = -1;
+ let mode: PairingMode = scenario === 'ask' ? 'ask' : scenario === 'code' ? 'code' : 'auto';
+ let requests: PairRequestSummary[] = scenario === 'ask' ? [...ASKING] : [];
+ let blocked: BlockedBrowser[] = scenario === 'kept' ? [...KEPT_OUT] : [];
+ let sessions: PairedSession[] = SESSIONS.map(({ pairedAgo, ...session }) => ({ ...session, pairedAt: ago(pairedAgo) }));
+ let sessionReads = 0;
+ const announce = (event: string) => listeners.forEach((listener) => listener(event));
+ const arrive = () => void sessions.push({ ...ARRIVING, pairedAt: ago(0) });
const ok = (stdout: string): CliOutput => ({ ok: true, code: 0, stdout, stderr: '' });
const later = <T>(value: T, ms = 350) => new Promise<T>((resolve) => setTimeout(() => resolve(value), instant ? 0 : ms));
@@ -46,11 +69,58 @@ export function mockBackend({ instant = false, fresh = location.hash === '#fresh
const replies: Record<string, (frame: Record<string, unknown>) => Record<string, unknown>> = {
status: () => ({
- status: { connected: true, daemonVersion: version, protocolVersion: 22, port: 8765, manifestInSync: true, extensionVersion: version, connectedBrowsers: 2, pairedBrowsers: 2, pairingPending: codePending },
+ status: {
+ connected: true,
+ daemonVersion: version,
+ protocolVersion: 22,
+ port: 8765,
+ manifestInSync: true,
+ extensionVersion: version,
+ connectedBrowsers: sessions.filter((session) => session.connected).length,
+ pairedBrowsers: sessions.length,
+ pairingPending: codePending,
+ pairing: { mode, approver: 'app' },
+ },
}),
- sessions: () => ({ sessions: SESSIONS.map((session) => ({ ...session, pairedAt: ago(session.pairedAgo), lastSeenAt: ago(4) })) }),
+ sessions: () => {
+ if (scenario === 'arrives' && ++sessionReads === 3) arrive();
+ return { sessions: sessions.map((session) => ({ ...session, lastSeenAt: ago(4) })) };
+ },
pair: () => ((codePending = true), { code: 'K7Q2M9', expiresAt: Date.now() + 10 * 60 * 1000 }),
- revoke: () => ({ revoked: 1 }),
+ revoke: ({ session }) => {
+ const revoked = sessions.filter((held) => !session || held.id === session);
+ sessions = sessions.filter((held) => !revoked.includes(held));
+ blocked = [...blocked, ...revoked.map(({ id, browser, origin }) => ({ installId: id, browser, origin, at: new Date().toISOString(), reason: 'revoked' as const }))];
+ return { revoked: revoked.length };
+ },
+ pairRequests: () => ({ requests }),
+ decide: ({ request, allow, label }) => {
+ const asked = requests.find((held) => held.id === request || held.installId === request);
+ const installId = asked?.installId ?? blocked.find((held) => held.installId === request)?.installId;
+ if (!installId) return { ok: false, error: 'No request or blocked browser has that id.' };
+ requests = requests.filter((held) => held !== asked);
+ blocked = blocked.filter((held) => held.installId !== installId);
+ if (asked && !allow) blocked = [...blocked, { installId, browser: asked.browser, origin: 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/', at: new Date().toISOString(), reason: 'denied' }];
+ if (asked && allow) {
+ const named = typeof label === 'string' && label.trim() ? label.trim() : undefined;
+ sessions.push({ id: installId, browser: asked.browser, label: named, origin: 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/', source: asked.source as Source, extensionVersion: asked.extensionVersion, pairedAt: ago(0), connected: true, pairedBy: 'approved' });
+ }
+ announce('pair-requests-changed');
+ return { ok: true };
+ },
+ pairing: ({ set }) => {
+ if (typeof set === 'string') {
+ mode = set as PairingMode;
+ announce('settings-changed');
+ }
+ return { mode, approver: 'app' };
+ },
+ blocked: () => ({ blocked }),
+ label: ({ session, label }) => {
+ const named = sessions.find((held) => held.id === session);
+ if (named) named.label = String(label).trim() || undefined;
+ return { ok: !!named };
+ },
preferences: () => ({ result: { ok: true, data: preferences } }),
setPreference: ({ change }) => {
const next = change as PreferenceChange;
@@ -81,12 +151,12 @@ export function mockBackend({ instant = false, fresh = location.hash === '#fresh
const browser = args[args.indexOf('--browser') + 1];
if (args.includes('--browser')) {
codePending = true;
- return ok(JSON.stringify({ version, extensionDir: null, daemon: { port: 8765, pid: 18115 }, alreadyPaired: true, chosen: { id: browser, unpacked: false, opened: true, connected: false }, pairingCode: 'R4TW7KXE', expiresAt: Date.now() + 10 * 60 * 1000, browsers: rows() }));
+ return ok(JSON.stringify({ version, extensionDir: null, daemon: { port: 8765, pid: 18115 }, alreadyPaired: true, chosen: { id: browser, unpacked: false, opened: true, connected: false }, pairingCode: 'R4TW7KXE', expiresAt: Date.now() + 10 * 60 * 1000, browsers: rows(sessions) }));
}
if (args.includes('--unpacked')) stamp = { version, installedAt: new Date().toISOString() };
- return ok(JSON.stringify({ version, extensionDir: stamp && `${home}\\browsentic\\extension\\chrome-mv3`, daemon: { port: 8765, pid: 18115 }, alreadyPaired: true, chosen: null, browsers: rows() }));
+ return ok(JSON.stringify({ version, extensionDir: stamp && `${home}\\browsentic\\extension\\chrome-mv3`, daemon: { port: 8765, pid: 18115 }, alreadyPaired: true, chosen: null, browsers: rows(sessions) }));
},
- browsers: () => ok(JSON.stringify({ running, browsers: rows(), unpacked: { dir: `${home}\\browsentic\\extension\\chrome-mv3`, version: stamp?.version ?? null } })),
+ browsers: () => ok(JSON.stringify({ running, browsers: rows(sessions), unpacked: { dir: `${home}\\browsentic\\extension\\chrome-mv3`, version: stamp?.version ?? null } })),
agent: (args) => {
if (args[1] === 'model') models[args[2] as AgentKind] = args[3];
return ok(JSON.stringify(agents()));
@@ -146,22 +216,68 @@ export function mockBackend({ instant = false, fresh = location.hash === '#fresh
controlRequest: (frame) => later((replies[String(frame.op)] ?? (() => ({})))(frame), 60),
controlClose: () => later(void (socket = false), 20),
trayStatus: () => later(undefined, 0),
+ pairRequests: () => later(undefined, 0),
+ announcePaired: () => later(undefined, 0),
checkUpdate: () => later(null),
installUpdate: () => later(undefined),
onControlEvent: (listener) => (listeners.add(listener), () => listeners.delete(listener)),
onTray: () => () => undefined,
+ onPairLink: () => () => undefined,
+ onPairingLaunch: () => () => undefined,
openUrl: async (url) => void window.open(url, '_blank'),
reveal: async () => undefined,
setWindowTheme: async () => undefined,
+ ask: (request) => {
+ requests = [...requests, request];
+ announce('pair-requests-changed');
+ },
+ arrive,
};
}
const ago = (seconds: number) => new Date(Date.now() - seconds * 1000).toISOString();
-/** A store copy in Chrome, an unpacked one in Brave a build behind, and Edge and Firefox yet to get it. */
-const SESSIONS = [
- { id: 's1', browser: 'Google Chrome', origin: 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/', source: 'chrome-web-store' as const, extensionVersion: '0.8.0', pairedAgo: 3 * 86400, connected: true },
- { id: 's2', browser: 'Brave', origin: 'chrome-extension://pplbfkdfiimmogofmehpibbmldcefgpc/', source: 'unpacked' as const, extensionVersion: '0.7.15', pairedAgo: 9 * 86400, connected: true },
+interface MockSession {
+ id: string;
+ browser?: string;
+ label?: string;
+ origin: string;
+ source: Source;
+ extensionVersion: string;
+ pairedAgo: number;
+ connected: boolean;
+ pairedBy?: PairedBy;
+}
+
+type PairedSession = Omit<MockSession, 'pairedAgo'> & { pairedAt: string };
+
+/** A store copy in Chrome that paired by itself, an unpacked one in Brave a build behind and named for work, and Edge and Firefox yet to get it. */
+const SESSIONS: MockSession[] = [
+ { id: 's1', browser: 'Google Chrome', origin: 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/', source: 'chrome-web-store', extensionVersion: '0.8.0', pairedAgo: 3 * 86400, connected: true, pairedBy: 'auto' },
+ { id: 's2', browser: 'Brave', label: 'Brave (work)', origin: 'chrome-extension://pplbfkdfiimmogofmehpibbmldcefgpc/', source: 'unpacked', extensionVersion: '0.7.15', pairedAgo: 9 * 86400, connected: true, pairedBy: 'code' },
+];
+
+const ARRIVING: Omit<MockSession, 'pairedAgo'> = {
+ id: '6f1c2a90-3b7e-4d1a-9c55-0e8f5d2b7a41',
+ browser: 'Microsoft Edge',
+ origin: 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/',
+ source: 'chrome-web-store',
+ extensionVersion: '0.8.0',
+ connected: true,
+ pairedBy: 'auto',
+};
+
+const asked = (seconds: number) => Date.now() - seconds * 1000;
+
+/** A second Brave profile with the store copy, then a Firefox that asked a little later. */
+const ASKING: PairRequestSummary[] = [
+ { id: 'Rq7bX2kp', installId: '3e9a51c0-77d2-4b8e-a1f4-6c0d2e9b5f13', browser: 'Brave', source: 'chrome-web-store', extensionVersion: '0.8.0', firstAt: asked(40), lastAskAt: asked(5), nonce: 'q0Zt8Hn3LwVb1yRk5sXe2A' },
+ { id: 'Fx4mN8cd', installId: 'a71f0b2e-5c94-4d3a-8e6b-29f1c7d04e88', browser: 'Firefox', source: 'firefox', extensionVersion: '0.8.0', firstAt: asked(12), lastAskAt: asked(2), nonce: 'Jm2Pw9Ux4Ec7Kb1Sd6Fh3Q' },
+];
+
+const KEPT_OUT: BlockedBrowser[] = [
+ { installId: 'c4d8e2f1-0a6b-4c3d-9e7f-1b2a3c4d5e6f', browser: 'Vivaldi', origin: 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/', at: new Date(Date.now() - 2 * 86400 * 1000).toISOString(), reason: 'revoked' },
+ { installId: '9b8a7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d', browser: 'Opera', origin: 'chrome-extension://npmocgldfflonjjmdadmdefpnfagnjmp/', at: new Date(Date.now() - 3 * 3600 * 1000).toISOString(), reason: 'denied' },
];
const STORES = {
@@ -169,9 +285,9 @@ const STORES = {
firefox: { store: 'Firefox add-on', storeUrl: 'https://github.com/imshaikot/browsentic/releases/download/v0.8.0/browsentic-0.8.0-firefox.xpi' },
};
-function rows(): BrowserRow[] {
+function rows(paired: Pick<MockSession, 'id' | 'browser' | 'source' | 'extensionVersion' | 'connected'>[]): BrowserRow[] {
const row = (id: BrowserRow['id'], label: string, brand: string, installed: boolean): BrowserRow => {
- const sessions = SESSIONS.filter((session) => session.browser === brand).map(({ id, source, extensionVersion, connected }) => ({ id, source, extensionVersion, connected }));
+ const sessions = paired.filter((session) => session.browser === brand).map(({ id, source, extensionVersion, connected }) => ({ id, source, extensionVersion, connected }));
const firefox = id === 'firefox';
const source = firefox ? 'firefox' : 'chrome-web-store';
return {
diff --git a/src/windows/ui/model.test.ts b/src/windows/ui/model.test.ts
index e146ba3..d31e93f 100644
--- a/src/windows/ui/model.test.ts
+++ b/src/windows/ui/model.test.ts
@@ -1,7 +1,7 @@
import { afterEach, describe, expect, it } from 'vitest';
-import type { Backend } from './backend';
-import { mockBackend } from './mock-backend';
+import type { Backend, PairLinkAct, PairRequestSummary, TrayStatus } from './backend';
+import { mockBackend, type MockBackend, type Scenario } from './mock-backend';
import { Model, TABS, outcome, parseJson, short, type State } from './model';
import { splitLine } from './views/logs';
@@ -134,10 +134,21 @@ describe('the running app', () => {
]);
});
- it('adds the extension to a browser by opening its store page and handing out the code to enter', async () => {
+ it('adds the extension to a browser by opening its store page, and says it connects by itself', async () => {
const model = await running();
await until(model, (state) => state.browserRows.length > 0);
await model.addExtension(model.offeredBrowsers.find((row) => row.id === 'edge')!);
+ expect([model.snapshot().pairing, model.snapshot().notice?.text]).toEqual([
+ undefined,
+ 'Press “Allow extensions from other stores” if Edge shows it at the top of the page, confirm, and press “Add to Chrome”. It connects to Browsentic Bridge by itself.',
+ ]);
+ });
+
+ it('hands out the code to enter with the store page when browsers pair only by code', async () => {
+ const model = start(mockBackend({ instant: true, scenario: 'code' }));
+ await model.runPreflight();
+ await until(model, (state) => state.pairingMode === 'code' && state.browserRows.length > 0);
+ await model.addExtension(model.offeredBrowsers.find((row) => row.id === 'edge')!);
expect([model.snapshot().pairing?.code, model.snapshot().notice?.text]).toEqual([
'R4TW7KXE',
'Press “Allow extensions from other stores” if Edge shows it at the top of the page, confirm, and press “Add to Chrome”. Then click Browsentic in Edge’s toolbar and enter the code below.',
@@ -257,3 +268,155 @@ describe('the Android tab', () => {
expect(start(mockBackend({ instant: true })).snapshot().androidReadyOnce).toBe(true);
});
});
+
+describe('pairing', () => {
+ /** The mock, with a record of what reached the control socket, the Rust side and the tray, and a hand on its links. */
+ function pairingBackend(scenario: Scenario) {
+ const backend = mockBackend({ instant: true, scenario });
+ const frames: Record<string, unknown>[] = [];
+ const handed: string[][] = [];
+ const announced: [string, string][] = [];
+ const trays: TrayStatus[] = [];
+ let follow: (act: PairLinkAct) => void = () => undefined;
+ let launched: () => void = () => undefined;
+ return {
+ frames,
+ handed,
+ announced,
+ trays,
+ follow: (act: PairLinkAct) => follow(act),
+ launch: () => launched(),
+ backend: {
+ ...backend,
+ controlRequest: (frame: Record<string, unknown>, timeoutMs?: number) => (frames.push(frame), backend.controlRequest(frame, timeoutMs)),
+ pairRequests: async (requests: PairRequestSummary[]) => void handed.push(requests.map((request) => request.id)),
+ announcePaired: async (session: string, name: string) => void announced.push([session, name]),
+ trayStatus: async (status: TrayStatus) => void trays.push(status),
+ onPairLink: (listener: (act: PairLinkAct) => void) => ((follow = listener), () => undefined),
+ onPairingLaunch: (listener: () => void) => ((launched = listener), () => undefined),
+ } satisfies MockBackend,
+ };
+ }
+
+ async function opened(backend: Backend) {
+ const model = start(backend);
+ await model.runPreflight();
+ await until(model, (state) => state.daemon === 'on' && !!state.pairingMode);
+ return model;
+ }
+
+ it('asks to be the approver on a new socket, and queues the browsers waiting oldest first', async () => {
+ const { backend, frames, handed, trays } = pairingBackend('ask');
+ const model = await opened(backend);
+ await until(model, (state) => state.pairRequests.length === 2);
+ expect(frames).toContainEqual({ op: 'pairRequests', watch: true, as: 'app' });
+ expect(model.snapshot().pairingMode).toBe('ask');
+ expect(model.snapshot().pairRequests.map((request) => request.browser)).toEqual(['Brave', 'Firefox']);
+ expect(handed.at(-1)).toEqual(['Rq7bX2kp', 'Fx4mN8cd']);
+ await until(model, () => trays.at(-1)?.waiting === 'Brave wants to connect…');
+ });
+
+ it('allows the first with the name typed for it, denies the next, and keeps the denied one out', async () => {
+ const { backend, frames, handed, trays } = pairingBackend('ask');
+ const model = await opened(backend);
+ await until(model, (state) => state.pairRequests.length === 2);
+ const [brave, firefox] = model.snapshot().pairRequests;
+
+ await model.decide(brave, true, ' Brave (personal) ');
+ expect(frames).toContainEqual({ op: 'decide', request: 'Rq7bX2kp', allow: true, label: 'Brave (personal)' });
+ expect(model.snapshot().notice?.text).toBe('Brave (personal) can connect to Browsentic Bridge now.');
+ expect(model.snapshot().pairRequests.map((request) => request.id)).toEqual(['Fx4mN8cd']);
+
+ await model.decide(firefox, false, 'ignored');
+ expect(frames).toContainEqual({ op: 'decide', request: 'Fx4mN8cd', allow: false });
+ expect(model.snapshot().notice?.text).toBe('Firefox is kept out. Reconnect it from Browsers if you change your mind.');
+ expect(model.snapshot().pairRequests).toEqual([]);
+ expect(model.snapshot().blocked).toMatchObject([{ browser: 'Firefox', reason: 'denied' }]);
+ expect(handed.at(-1)).toEqual([]);
+ await until(model, () => trays.at(-1)?.waiting === null);
+
+ await model.refresh();
+ expect(model.snapshot().sessions.find((session) => session.browser === 'Brave' && session.pairedBy === 'approved')?.label).toBe('Brave (personal)');
+ });
+
+ it('asks to be the approver again when the Bridge starts the app for a browser', async () => {
+ const { backend, frames, launch } = pairingBackend('auto');
+ const model = await opened(backend);
+ const watching = () => frames.filter((frame) => frame.op === 'pairRequests' && frame.watch === true).length;
+ await until(model, () => watching() === 1);
+ launch();
+ await until(model, () => watching() === 2);
+ });
+
+ it('reads the list again when the Bridge says it changed', async () => {
+ const { backend } = pairingBackend('auto');
+ const model = await opened(backend);
+ backend.ask({ id: 'Op9', installId: 'f00dfeed-0000-4000-8000-000000000001', browser: 'Opera', source: 'unpacked', extensionVersion: '0.8.0', firstAt: Date.now(), lastAskAt: Date.now(), nonce: 'n' });
+ await until(model, (state) => state.pairRequests[0]?.browser === 'Opera');
+ });
+
+ it('changes how browsers pair, and says so through the Bridge', async () => {
+ const { backend, frames } = pairingBackend('auto');
+ const model = await opened(backend);
+ expect(model.pairsByItself).toBe(true);
+ await model.setPairingMode('code');
+ expect(frames).toContainEqual({ op: 'pairing', set: 'code' });
+ expect(model.snapshot().pairingMode).toBe('code');
+ expect(model.pairsByItself).toBe(false);
+ });
+
+ it('keeps an unpaired browser out, and lets a kept-out one back in with Reconnect', async () => {
+ const { backend, frames } = pairingBackend('kept');
+ const model = await opened(backend);
+ await until(model, (state) => state.blocked.length === 2);
+ const vivaldi = model.snapshot().blocked.find((browser) => browser.browser === 'Vivaldi')!;
+ await model.reconnect(vivaldi);
+ expect(frames).toContainEqual({ op: 'decide', request: vivaldi.installId, allow: true });
+ expect(model.snapshot().notice?.text).toBe('Vivaldi can connect again.');
+ expect(model.snapshot().blocked.map((browser) => browser.browser)).toEqual(['Opera']);
+
+ await model.revoke(model.snapshot().sessions.find((session) => session.id === 's1'));
+ expect(model.snapshot().blocked).toMatchObject([{ browser: 'Opera' }, { browser: 'Google Chrome', reason: 'revoked' }]);
+ });
+
+ it('names a browser, and shows the name instead of the browser’s own', async () => {
+ const { backend, frames } = pairingBackend('auto');
+ const model = await opened(backend);
+ await until(model, (state) => state.sessions.length > 0);
+ await model.rename(model.snapshot().sessions[0], ' Chrome at home ');
+ expect(frames).toContainEqual({ op: 'label', session: 's1', label: 'Chrome at home' });
+ expect(model.snapshot().sessions[0].label).toBe('Chrome at home');
+ });
+
+ it('announces a browser that paired by itself once, and never the ones it found', async () => {
+ const { backend, announced } = pairingBackend('auto');
+ const model = await opened(backend);
+ await until(model, (state) => state.sessions.length === 2);
+ expect(announced).toEqual([]);
+ backend.arrive();
+ await model.refresh();
+ await model.refresh();
+ expect(model.snapshot().notice?.text).toBe('Microsoft Edge connected to Browsentic Bridge by itself.');
+ expect(announced).toEqual([['6f1c2a90-3b7e-4d1a-9c55-0e8f5d2b7a41', 'Microsoft Edge']]);
+ });
+
+ it('acts on a notification’s button only as the Rust side judged it', async () => {
+ const { backend, frames, follow } = pairingBackend('ask');
+ const model = await opened(backend);
+ await until(model, (state) => state.pairRequests.length === 2);
+
+ follow({ kind: 'show', request: 'Rq7bX2kp' });
+ follow({ kind: 'decide', request: 'nobody', allow: true });
+ expect(frames.filter((frame) => frame.op === 'decide')).toEqual([]);
+
+ follow({ kind: 'decide', request: 'Fx4mN8cd', allow: true });
+ await until(model, (state) => state.pairRequests.length === 1);
+ expect(frames).toContainEqual({ op: 'decide', request: 'Fx4mN8cd', allow: true });
+
+ follow({ kind: 'browsers' });
+ expect(model.snapshot().tab).toBe('browsers');
+
+ follow({ kind: 'unpair', session: 's2' });
+ await until(model, (state) => !state.sessions.some((session) => session.id === 's2'));
+ });
+});
diff --git a/src/windows/ui/model.ts b/src/windows/ui/model.ts
index a86a7c4..fe23fc4 100644
--- a/src/windows/ui/model.ts
+++ b/src/windows/ui/model.ts
@@ -1,6 +1,7 @@
import { useSyncExternalStore } from 'react';
import { AGENT_LIST, type AgentDescriptor, type AgentKind } from '@/lib/agents/catalog';
+import { isPairingMode } from '@/lib/pairing';
import type { GuardrailValue } from '@/lib/settings/guardrails';
import type { PreferenceChange } from '@/lib/settings/preferences';
import type { ThemeId } from '@/lib/settings/theme';
@@ -10,6 +11,7 @@ import type {
AgentListing,
AppInfo,
Backend,
+ BlockedBrowser,
Browser,
BridgeStatus,
CliOutput,
@@ -19,7 +21,10 @@ import type {
InstallStamp,
Lockfile,
NodeInstall,
+ PairLinkAct,
+ PairRequestSummary,
PairingCode,
+ PairingMode,
Preferences,
Release,
SessionSummary,
@@ -77,6 +82,12 @@ export interface State {
status?: BridgeStatus;
sessions: SessionSummary[];
pairing?: PairingCode;
+ /** Absent while the Bridge is off, and from a Bridge before browsers could pair by themselves. */
+ pairingMode?: PairingMode;
+ /** Browsers waiting for someone to let them in, oldest first: the dialog shows the first. */
+ pairRequests: PairRequestSummary[];
+ /** Browsers unpaired or denied here, kept out until someone reconnects them. */
+ blocked: BlockedBrowser[];
agents?: AgentListing;
/** `browsentic android --json` while the Android tab is open; the Bridge looks for phones only then. */
android?: AndroidJson;
@@ -165,6 +176,8 @@ export const initialState = (): State => ({
fixing: false,
daemon: 'off',
sessions: [],
+ pairRequests: [],
+ blocked: [],
preferencesUnsupported: false,
grants: [],
browsers: [],
@@ -187,6 +200,8 @@ export class Model {
private noticeTimer?: ReturnType<typeof setTimeout>;
private noticeCount = 0;
private started = false;
+ /** Every session seen since the app opened, so one that is new can be told apart from the ones it found. */
+ private seenSessions?: Set<string>;
constructor(
private readonly backend: Backend,
@@ -196,6 +211,10 @@ export class Model {
if (action === 'toggle') void this.setDaemon(this.state.daemon === 'off');
if (action === 'restart') void this.restartDaemon();
});
+ backend.onPairLink((act) => this.follow(act));
+ backend.onPairingLaunch(() => {
+ if (this.state.phase === 'main') void this.refresh().then(() => this.watchPairRequests());
+ });
}
subscribe = (listener: () => void) => {
@@ -210,7 +229,7 @@ export class Model {
const before = this.state;
this.state = { ...this.state, ...next };
this.listeners.forEach((listener) => listener());
- if (before.daemon !== this.state.daemon || before.status !== this.state.status || before.phase !== this.state.phase) {
+ if (before.daemon !== this.state.daemon || before.status !== this.state.status || before.phase !== this.state.phase || before.pairRequests !== this.state.pairRequests) {
void this.syncTray();
}
}
@@ -233,6 +252,11 @@ export class Model {
return !!stamp && sessions.some((session) => session.connected && session.source === 'unpacked' && session.extensionVersion !== stamp.version);
}
+ /** Browsers connect through the native host by themselves, with or without someone allowing each first. */
+ get pairsByItself() {
+ return this.state.pairingMode === 'auto' || this.state.pairingMode === 'ask';
+ }
+
/** The browsers worth a row: found on this computer or already paired, else the usual few to try. */
get offeredBrowsers() {
const rows = this.state.browserRows;
@@ -409,9 +433,15 @@ export class Model {
this.stopEvents?.();
this.stopEvents = this.backend.onControlEvent((event) => {
if (event === 'android-changed') return void this.loadAndroid();
+ if (event === 'pair-requests-changed') {
+ void this.loadPairRequests();
+ void this.loadBlocked();
+ return;
+ }
if (event !== 'settings-changed') return;
void this.loadPreferences();
void this.loadAgents();
+ void this.loadPairingMode();
});
clearInterval(this.poller);
void this.refresh();
@@ -435,6 +465,7 @@ export class Model {
try {
if (await this.backend.controlConnect()) {
void this.loadPreferences(true);
+ void this.watchPairRequests();
if (this.watchingAndroid) void this.watchAndroid(true);
}
const status = (await this.control({ op: 'status' })).status as BridgeStatus;
@@ -446,9 +477,11 @@ export class Model {
status,
sessions,
stamp,
+ pairingMode: status.pairing?.mode,
daemon: state.daemon === 'stopping' ? 'stopping' : 'on',
pairing: state.pairing && status.pairingPending && state.pairing.expiresAt > Date.now() ? state.pairing : undefined,
}));
+ this.announceArrivals(sessions);
if (!this.state.agents) await this.loadAgents();
if (changed) void this.loadBrowsers();
} catch {
@@ -459,7 +492,8 @@ export class Model {
private markOff() {
if (this.state.daemon === 'starting') return;
- this.set({ daemon: 'off', lock: undefined, status: undefined, sessions: [], pairing: undefined, preferences: undefined });
+ this.set({ daemon: 'off', lock: undefined, status: undefined, sessions: [], pairing: undefined, preferences: undefined, pairingMode: undefined, blocked: [] });
+ if (this.state.pairRequests.length) this.showPairRequests([]);
}
async setDaemon(on: boolean) {
@@ -507,6 +541,112 @@ export class Model {
this.say(count === 0 ? 'Nothing to unpair.' : `Unpaired ${count} browser${count === 1 ? '' : 's'}.`);
});
await this.refresh();
+ await this.loadBlocked();
+ }
+
+ // Pairing
+
+ /** Every new socket asks as the app, so the Bridge tells this window, not a terminal, when a browser asks. */
+ private async watchPairRequests() {
+ await this.readPairRequests({ op: 'pairRequests', watch: true, as: 'app' });
+ await this.loadBlocked();
+ }
+
+ loadPairRequests() {
+ return this.readPairRequests({ op: 'pairRequests' });
+ }
+
+ private async readPairRequests(frame: Record<string, unknown>) {
+ try {
+ const reply = await this.control(frame);
+ this.showPairRequests(Array.isArray(reply.requests) ? (reply.requests as PairRequestSummary[]) : []);
+ } catch {
+ /* A Bridge from before browsers could pair by themselves never answers, and nobody is waiting on it. */
+ }
+ }
+
+ private showPairRequests(requests: PairRequestSummary[]) {
+ const pairRequests = [...requests].sort((a, b) => a.firstAt - b.firstAt);
+ this.set({ pairRequests });
+ void this.backend.pairRequests(pairRequests).catch(() => undefined);
+ }
+
+ async loadBlocked() {
+ try {
+ const reply = await this.control({ op: 'blocked' });
+ this.set({ blocked: Array.isArray(reply.blocked) ? (reply.blocked as BlockedBrowser[]) : [] });
+ } catch {
+ /* The Kept out list stays as it was until the Bridge answers. */
+ }
+ }
+
+ async loadPairingMode() {
+ try {
+ const reply = await this.control({ op: 'pairing' });
+ if (isPairingMode(reply.mode)) this.set({ pairingMode: reply.mode });
+ } catch {
+ /* The next status read carries the mode too. */
+ }
+ }
+
+ setPairingMode(mode: PairingMode) {
+ return this.perform('pairing', async () => {
+ const reply = accepted(await this.control({ op: 'pairing', set: mode }), 'Browsentic Bridge kept the pairing setting as it was.');
+ if (isPairingMode(reply.mode)) this.set({ pairingMode: reply.mode });
+ });
+ }
+
+ /** Allow sends the name typed in the dialog; Deny keeps the browser out until someone reconnects it. */
+ decide(request: PairRequestSummary, allow: boolean, label?: string) {
+ const named = label?.trim() || undefined;
+ return this.perform(`decide:${request.id}`, async () => {
+ accepted(await this.control({ op: 'decide', request: request.id, allow, ...(allow && named ? { label: named } : {}) }), 'Browsentic Bridge could not settle that request.');
+ const name = (allow && named) || browserName(request);
+ this.say(allow ? `${name} can connect to Browsentic Bridge now.` : `${name} is kept out. Reconnect it from Browsers if you change your mind.`);
+ this.showPairRequests(this.state.pairRequests.filter((held) => held.id !== request.id));
+ await Promise.all([this.loadPairRequests(), this.loadBlocked()]);
+ });
+ }
+
+ reconnect(browser: BlockedBrowser) {
+ return this.perform(`reconnect:${browser.installId}`, async () => {
+ accepted(await this.control({ op: 'decide', request: browser.installId, allow: true }), 'Browsentic Bridge could not let that browser back in.');
+ this.say(`${browser.browser ?? 'That browser'} can connect again.`);
+ await this.loadBlocked();
+ });
+ }
+
+ rename(session: SessionSummary, label: string) {
+ return this.perform(`label:${session.id}`, async () => {
+ accepted(await this.control({ op: 'label', session: session.id, label: label.trim() }), 'Browsentic Bridge could not rename that browser.');
+ await this.refresh();
+ });
+ }
+
+ /** The sessions read first are the ones the app found; any after that are new, and one that paired by itself is announced once. */
+ private announceArrivals(sessions: SessionSummary[]) {
+ const keyOf = (session: SessionSummary) => `${session.id}@${session.pairedAt}`;
+ const seen = this.seenSessions;
+ this.seenSessions = new Set([...(seen ?? []), ...sessions.map(keyOf)]);
+ if (!seen) return;
+ for (const session of sessions.filter((candidate) => candidate.pairedBy === 'auto' && !seen.has(keyOf(candidate)))) {
+ const name = sessionName(session);
+ this.say(`${name} connected to Browsentic Bridge by itself.`);
+ void this.backend.announcePaired(session.id, name).catch(() => undefined);
+ }
+ }
+
+ /** A notification's button, once the Rust side has matched its nonce; anything else only opens the window. */
+ private follow(act: PairLinkAct) {
+ if (act.kind === 'browsers') return this.setTab('browsers');
+ if (act.kind === 'decide') {
+ const request = this.state.pairRequests.find((held) => held.id === act.request);
+ if (request) void this.decide(request, act.allow);
+ }
+ if (act.kind === 'unpair') {
+ const session = this.state.sessions.find((held) => held.id === act.session);
+ if (session) void this.revoke(session);
+ }
}
async loadAgents() {
@@ -653,6 +793,8 @@ export class Model {
return this.perform(`add:${row.id}`, async () => {
const result = parseJson<SetupResult>(await this.backend.cli(['setup', '--browser', row.id, '--no-wait', '--no-self-update', '--json'], 120), 'setup');
if (!result.chosen?.opened) await this.backend.openUrl(row.storeUrl);
+ if (this.state.pairingMode === 'auto') return this.say(`${row.steps[0]} It connects to Browsentic Bridge by itself.`);
+ if (this.state.pairingMode === 'ask') return this.say(`${row.steps[0]} Then allow it here when it asks to connect.`);
if (result.pairingCode && result.expiresAt) this.set({ pairing: { code: result.pairingCode, expiresAt: result.expiresAt } });
this.say(`${row.steps[0]} Then click Browsentic in ${row.label}’s toolbar and enter the code below.`);
});
@@ -828,7 +970,7 @@ export class Model {
}
private async syncTray() {
- const { daemon, status, phase } = this.state;
+ const { daemon, status, phase, pairRequests } = this.state;
const label = { off: 'Off', starting: 'Starting', on: 'Running', stopping: 'Stopping' }[daemon];
const link = status ? ` · extension ${status.connected ? 'connected' : 'not connected'}` : '';
await this.backend
@@ -837,6 +979,7 @@ export class Model {
toggle: daemon === 'on' ? 'Turn Off' : 'Turn On',
canToggle: phase === 'main' && (daemon === 'on' || daemon === 'off'),
canRestart: daemon === 'on',
+ waiting: pairRequests[0] ? `${browserName(pairRequests[0])} wants to connect…` : null,
})
.catch(() => undefined);
}
@@ -850,6 +993,17 @@ interface SetupResult {
expiresAt?: number;
}
+export const browserName = (request: Pick<PairRequestSummary, 'browser'>) => request.browser ?? 'A browser';
+
+export const sessionName = (session: Pick<SessionSummary, 'label' | 'browser'>) => session.label ?? session.browser ?? 'A browser';
+
+/** The pairing ops answer `{ok, error}` or `{mode, error}`, a refusal in words rather than an ActionResult. */
+function accepted(reply: Record<string, unknown>, fallback: string) {
+ if (typeof reply.error === 'string' && reply.error) throw new Error(reply.error);
+ if (reply.ok === false) throw new Error(fallback);
+ return reply;
+}
+
/** Which copies are connected, as one string: a change is what makes the browser rows worth reading again. */
const linkOf = (sessions: SessionSummary[]) => sessions.map((session) => `${session.id}:${session.connected}`).join(',');
diff --git a/src/windows/ui/views/browsers.tsx b/src/windows/ui/views/browsers.tsx
index 58422cb..1057693 100644
--- a/src/windows/ui/views/browsers.tsx
+++ b/src/windows/ui/views/browsers.tsx
@@ -1,19 +1,30 @@
import { useState } from 'react';
-import { Globe } from 'lucide-react';
+import { Globe, PencilLine, RotateCcw } from 'lucide-react';
import { formatWhen } from '@/lib/format-when';
import { SOURCE_LABEL } from '@/lib/stores';
-import { Card, ConfirmDialog, EmptyState, GlowDot, OfflineHint, Pill, QuietButton, SectionTitle } from '../components';
-import type { Model, State } from '../model';
-import type { SessionSummary } from '../backend';
+import { Card, ConfirmDialog, EmptyState, GlowDot, OfflineHint, Pill, QuietButton, SectionTitle, TextField } from '../components';
+import { sessionName, type Model, type State } from '../model';
+import type { BlockedBrowser, PairedBy, PairingMode, SessionSummary } from '../backend';
import { ConnectCard } from './overview';
const extensionId = (origin: string) => origin.replace(/^[a-z-]+-extension:\/\//, '').replace(/\/$/, '');
const ago = (iso: string) => formatWhen(Date.parse(iso));
+const PAIRED_BY: Record<PairedBy, string> = { auto: 'Paired by itself', approved: 'Allowed', code: 'Paired with a code' };
+
+const NONE_PAIRED: Record<PairingMode, string> = {
+ auto: 'Add the extension from the Overview tab, and it connects by itself.',
+ ask: 'Add the extension from the Overview tab, then allow it here when it asks to connect.',
+ code: 'Add the extension from the Overview tab, or get a code above and enter it in the Browsentic side panel.',
+};
+
+type Asking = { kind: 'unpair' | 'rename'; session: SessionSummary } | { kind: 'unpair-all' };
+
export function BrowsersView({ model, state }: { model: Model; state: State }) {
- const [confirming, setConfirming] = useState(false);
+ const [asking, setAsking] = useState<Asking>();
if (state.daemon !== 'on') return <OfflineHint what="Paired browsers" model={model} daemonOff={state.daemon === 'off'} />;
+ const close = () => setAsking(undefined);
return (
<div className="space-y-4.5">
@@ -22,54 +33,134 @@ export function BrowsersView({ model, state }: { model: Model; state: State }) {
<div className="space-y-3.5">
<div className="flex items-start gap-3">
<div className="min-w-0 flex-1">
- <SectionTitle title="Paired browsers" subtitle="Each one holds a key of its own. Unpairing drops the key and disconnects it at once." />
+ <SectionTitle
+ title="Paired browsers"
+ subtitle="Each one holds a key of its own. Unpairing drops the key, disconnects it at once, and keeps it out until you reconnect it."
+ />
</div>
{state.sessions.length > 1 && (
- <QuietButton tint="danger" onClick={() => setConfirming(true)}>
+ <QuietButton tint="danger" onClick={() => setAsking({ kind: 'unpair-all' })}>
Unpair all
</QuietButton>
)}
</div>
{state.sessions.length === 0 ? (
- <EmptyState icon={Globe} title="No browser is paired" detail="Add the extension from the Overview tab, or get a code above and enter it in the Browsentic side panel." />
+ <EmptyState icon={Globe} title="No browser is paired" detail={NONE_PAIRED[state.pairingMode ?? 'code']} />
) : (
- state.sessions.map((session) => <SessionRow key={session.id} session={session} model={model} busy={state.busy.includes('revoke')} />)
+ state.sessions.map((session) => (
+ <SessionRow
+ key={session.id}
+ session={session}
+ busy={state.busy.includes('revoke') || state.busy.includes(`label:${session.id}`)}
+ onRename={() => setAsking({ kind: 'rename', session })}
+ onUnpair={() => setAsking({ kind: 'unpair', session })}
+ />
+ ))
)}
</div>
</Card>
- {confirming && (
+ {state.blocked.length > 0 && <KeptOut model={model} state={state} />}
+ {asking?.kind === 'unpair-all' && (
<ConfirmDialog
title="Unpair every browser?"
- message="Each one will need a new pairing code to connect again."
+ message="They won’t reconnect by themselves until you reconnect them."
action="Unpair all"
- onCancel={() => setConfirming(false)}
+ onCancel={close}
onConfirm={() => {
- setConfirming(false);
+ close();
void model.revoke();
}}
/>
)}
+ {asking?.kind === 'unpair' && (
+ <ConfirmDialog
+ title={`Unpair ${sessionName(asking.session)}?`}
+ message="It won’t reconnect by itself until you reconnect it."
+ action="Unpair"
+ onCancel={close}
+ onConfirm={() => {
+ close();
+ void model.revoke(asking.session);
+ }}
+ />
+ )}
+ {asking?.kind === 'rename' && <RenameDialog session={asking.session} model={model} onClose={close} />}
</div>
);
}
-function SessionRow({ session, model, busy }: { session: SessionSummary; model: Model; busy: boolean }) {
+function SessionRow({ session, busy, onRename, onUnpair }: { session: SessionSummary; busy: boolean; onRename: () => void; onUnpair: () => void }) {
+ const name = session.label ?? session.browser;
+ const paired = `${PAIRED_BY[session.pairedBy ?? 'code']} ${ago(session.pairedAt)}`;
return (
<div className="flex items-center gap-3 rounded-xl bg-ground-2 p-3">
<GlowDot tint={session.connected ? 'lime' : 'faint'} pulsing={session.connected} />
<div className="min-w-0 flex-1 space-y-0.75">
- {session.browser && <p className="text-[13px] font-medium text-ink">{session.browser}</p>}
- <p className={session.browser ? 'truncate font-mono text-xs text-ink-dim select-text' : 'truncate font-mono text-xs text-ink select-text'}>
+ {name && <p className="truncate text-[13px] font-medium text-ink">{name}</p>}
+ <p className={name ? 'truncate font-mono text-xs text-ink-dim select-text' : 'truncate font-mono text-xs text-ink select-text'}>
+ {session.label && session.browser && session.label !== session.browser && <span className="font-sans">{session.browser} · </span>}
{extensionId(session.origin)}
</p>
<p className="text-[11.5px] text-ink-dim">
- {SOURCE_LABEL[session.source ?? 'unpacked']} · v{session.extensionVersion} · paired {ago(session.pairedAt)} · seen {ago(session.lastSeenAt)}
+ {SOURCE_LABEL[session.source ?? 'unpacked']} · v{session.extensionVersion} · {paired} · seen {ago(session.lastSeenAt)}
</p>
</div>
<Pill text={session.connected ? 'Connected' : 'Away'} tint={session.connected ? 'lime' : 'dim'} />
- <QuietButton tint="danger" disabled={busy} onClick={() => void model.revoke(session)}>
+ <QuietButton icon={PencilLine} disabled={busy} onClick={onRename}>
+ Rename
+ </QuietButton>
+ <QuietButton tint="danger" disabled={busy} onClick={onUnpair}>
Unpair
</QuietButton>
</div>
);
}
+
+function RenameDialog({ session, model, onClose }: { session: SessionSummary; model: Model; onClose: () => void }) {
+ const [label, setLabel] = useState(session.label ?? session.browser ?? '');
+ return (
+ <ConfirmDialog
+ title={`Rename ${sessionName(session)}`}
+ message="The name this computer shows for it, to tell two profiles of one browser apart. Leave it empty to use the browser’s own name."
+ action="Save"
+ tint="brand"
+ onCancel={onClose}
+ onConfirm={() => {
+ onClose();
+ void model.rename(session, label);
+ }}
+ >
+ <TextField label="Name" value={label} placeholder={session.browser} maxLength={40} onChange={setLabel} />
+ </ConfirmDialog>
+ );
+}
+
+function KeptOut({ model, state }: { model: Model; state: State }) {
+ return (
+ <Card>
+ <div className="space-y-3.5">
+ <SectionTitle title="Kept out" subtitle="Browsers you unpaired or denied. None of them connects by itself until you reconnect it." />
+ {state.blocked.map((browser) => (
+ <KeptOutRow key={browser.installId} browser={browser} model={model} busy={state.busy.includes(`reconnect:${browser.installId}`)} />
+ ))}
+ </div>
+ </Card>
+ );
+}
+
+function KeptOutRow({ browser, model, busy }: { browser: BlockedBrowser; model: Model; busy: boolean }) {
+ return (
+ <div className="flex items-center gap-3 rounded-xl bg-ground-2 p-3">
+ <GlowDot tint="faint" />
+ <div className="min-w-0 flex-1 space-y-0.75">
+ <p className="truncate text-[13px] font-medium text-ink">{browser.browser ?? 'A browser'}</p>
+ <p className="text-[11.5px] text-ink-dim">
+ {browser.reason === 'revoked' ? 'Unpaired' : 'Denied'} {ago(browser.at)} · <span className="font-mono select-text">{browser.installId.slice(0, 8)}</span>
+ </p>
+ </div>
+ <QuietButton icon={RotateCcw} tint="brand" disabled={busy} onClick={() => void model.reconnect(browser)}>
+ Reconnect
+ </QuietButton>
+ </div>
+ );
+}
diff --git a/src/windows/ui/views/overview.tsx b/src/windows/ui/views/overview.tsx
index a614e08..8b9b644 100644
--- a/src/windows/ui/views/overview.tsx
+++ b/src/windows/ui/views/overview.tsx
@@ -24,7 +24,9 @@ export function OverviewView({ model, state }: { model: Model; state: State }) {
const subtitle = {
on: connected
? 'Open the side panel in your browser and say what you want. This window can close: Browsentic Bridge keeps running.'
- : 'Browsentic Bridge is running. Add the extension to your browser below and pair it once, and the side panel comes alive.',
+ : model.pairsByItself
+ ? 'Browsentic Bridge is running. Add the extension to your browser below, and the side panel comes alive.'
+ : 'Browsentic Bridge is running. Add the extension to your browser below and pair it once, and the side panel comes alive.',
off: 'Turn it on and the side panel in your browser can reach the agent you already run.',
starting: 'One moment.',
stopping: 'One moment.',
@@ -137,18 +139,33 @@ function Stat({ label, value, detail, icon: Icon, tint = 'brand' }: { label: str
);
}
+const CODE_STEPS = 'Click Browsentic in your browser’s toolbar (the puzzle piece lists it), enter the code, and press Connect. It works once and expires in ten minutes.';
+
+/** The code always works; once browsers connect by themselves it waits, secondary, until someone asks for one. */
export function ConnectCard({ model, state }: { model: Model; state: State }) {
+ const asking = state.busy.includes('pair');
+ if (model.pairsByItself && !state.pairing) {
+ return (
+ <Card>
+ <div className="flex items-center gap-4">
+ <div className="min-w-0 flex-1">
+ <SectionTitle title="Pair with a code" subtitle="Browsers with Browsentic connect by themselves. Need a code instead?" />
+ </div>
+ <QuietButton icon={KeyRound} disabled={asking} onClick={() => void model.newPairingCode()}>
+ Get a pairing code
+ </QuietButton>
+ </div>
+ </Card>
+ );
+ }
return (
<Card>
<div className="space-y-4">
- <SectionTitle
- title="Pair a browser"
- subtitle="Click Browsentic in your browser’s toolbar (the puzzle piece lists it), enter the code, and press Connect. It works once and expires in ten minutes."
- />
+ <SectionTitle title={model.pairsByItself ? 'Pair with a code' : 'Pair a browser'} subtitle={CODE_STEPS} />
{state.pairing ? (
<PairingCodeView pairing={state.pairing} model={model} />
) : (
- <PrimaryButton icon={KeyRound} disabled={state.busy.includes('pair')} onClick={() => void model.newPairingCode()}>
+ <PrimaryButton icon={KeyRound} disabled={asking} onClick={() => void model.newPairingCode()}>
Get a pairing code
</PrimaryButton>
)}
@@ -203,7 +220,11 @@ function ExtensionCard({ model, state }: { model: Model; state: State }) {
const unpacked = shown ?? !!state.stamp;
const subtitle = state.sessions.some((session) => session.connected)
? 'In your browser and talking to Browsentic Bridge. Store copies update themselves.'
- : 'Add it from your browser’s store, then click Browsentic in the toolbar and enter the pairing code once.';
+ : {
+ auto: 'Add it from your browser’s store, and it connects to Browsentic Bridge by itself.',
+ ask: 'Add it from your browser’s store, then allow it here when it asks to connect.',
+ code: 'Add it from your browser’s store, then click Browsentic in the toolbar and enter the pairing code once.',
+ }[state.pairingMode ?? 'code'];
return (
<Card>
@@ -231,7 +252,7 @@ function ExtensionCard({ model, state }: { model: Model; state: State }) {
<div className="space-y-2">
<Step number={1}>Open chrome://extensions and turn on Developer mode.</Step>
<Step number={2}>Press “Load unpacked”, then paste the folder above into the picker’s address bar.</Step>
- <Step number={3}>Click Browsentic in the toolbar and enter a pairing code.</Step>
+ <Step number={3}>{model.pairsByItself ? 'It connects by itself, or with a pairing code from the Browsers tab.' : 'Click Browsentic in the toolbar and enter a pairing code.'}</Step>
</div>
<div className="flex flex-wrap items-center gap-2">
{state.browsers
diff --git a/src/windows/ui/views/pair-request.tsx b/src/windows/ui/views/pair-request.tsx
new file mode 100644
index 0000000..7b20036
--- /dev/null
+++ b/src/windows/ui/views/pair-request.tsx
@@ -0,0 +1,60 @@
+import { useState } from 'react';
+
+import { formatWhen } from '@/lib/format-when';
+import { SOURCE_LABEL, type Source } from '@/lib/stores';
+import { ConfirmDialog, TextField } from '../components';
+import { browserName, type Model, type State } from '../model';
+import type { PairRequestSummary } from '../backend';
+
+const sourceLabel = (source: string) => {
+ const label = SOURCE_LABEL[source as Source] ?? source;
+ return label.charAt(0).toUpperCase() + label.slice(1);
+};
+
+/** The first browser waiting to be let in; the rest wait their turn behind it. */
+export function PairRequestQueue({ model, state }: { model: Model; state: State }) {
+ const [request, ...behind] = state.pairRequests;
+ if (state.phase !== 'main' || !request) return null;
+ return <PairRequestDialog key={request.id} request={request} behind={behind.length} model={model} busy={state.busy.includes(`decide:${request.id}`)} />;
+}
+
+function PairRequestDialog({ request, behind, model, busy }: { request: PairRequestSummary; behind: number; model: Model; busy: boolean }) {
+ const [name, setName] = useState(request.browser ?? '');
+ const there = request.browser ?? 'this browser';
+
+ return (
+ <ConfirmDialog
+ title={`${browserName(request)} wants to connect to Browsentic Bridge`}
+ message={`Allow it to use your agent and drive this browser? If you didn’t just install or open Browsentic in ${there}, don’t allow it.`}
+ action="Allow"
+ cancel="Deny"
+ tint="brand"
+ dismissible={false}
+ busy={busy}
+ onConfirm={() => void model.decide(request, true, name)}
+ onCancel={() => void model.decide(request, false)}
+ >
+ <dl className="grid grid-cols-[auto_1fr] gap-x-5 gap-y-1.5 rounded-xl bg-ground-2 px-3.5 py-3 text-[12px]">
+ <Detail term="From" value={sourceLabel(request.source)} />
+ <Detail term="Version" value={`v${request.extensionVersion}`} />
+ <Detail term="Install" value={request.installId.slice(0, 8)} mono />
+ <Detail term="Asked" value={formatWhen(request.firstAt)} />
+ </dl>
+ <TextField label="Name it" value={name} placeholder={browserName(request)} maxLength={40} onChange={setName} />
+ {behind > 0 && (
+ <p className="text-[11.5px] text-ink-faint">
+ {behind === 1 ? 'One more browser is' : `${behind} more browsers are`} waiting after this one.
+ </p>
+ )}
+ </ConfirmDialog>
+ );
+}
+
+function Detail({ term, value, mono = false }: { term: string; value: string; mono?: boolean }) {
+ return (
+ <>
+ <dt className="text-ink-faint">{term}</dt>
+ <dd className={mono ? 'font-mono text-ink select-text' : 'text-ink'}>{value}</dd>
+ </>
+ );
+}
diff --git a/src/windows/ui/views/settings.tsx b/src/windows/ui/views/settings.tsx
index 84eefa1..2602b56 100644
--- a/src/windows/ui/views/settings.tsx
+++ b/src/windows/ui/views/settings.tsx
@@ -5,8 +5,10 @@ import { GuardrailPolicy } from '@/extension/components/guardrail-policy';
import { ThemePicker } from '@/extension/components/theme-picker';
import { Switch } from '@/extension/components/ui/switch';
import { DEFAULT_THEME } from '@/lib/settings/theme';
+import { cn } from '@/lib/utils';
import { Card, ConfirmDialog, CopyButton, OfflineHint, PathRow, PrimaryButton, QuietButton, SectionTitle, Segmented, Spinner } from '../components';
import { short, type Appearance, type Model, type State } from '../model';
+import type { PairingMode } from '../backend';
import { UpdateCard } from './update-card';
export function SettingsView({ model, state }: { model: Model; state: State }) {
@@ -42,6 +44,8 @@ export function SettingsView({ model, state }: { model: Model; state: State }) {
</div>
</Card>
+ <PairingSettings model={model} state={state} />
+
<BrowserSettings model={model} state={state} />
<Card>
@@ -135,6 +139,55 @@ function SwitchRow({ title, subtitle, checked, onChange }: { title: string; subt
);
}
+const PAIRING: { mode: PairingMode; title: string; detail: string }[] = [
+ { mode: 'auto', title: 'Automatic', detail: 'A browser with Browsentic connects by itself.' },
+ { mode: 'ask', title: 'Ask me', detail: 'You allow each new browser here first.' },
+ { mode: 'code', title: 'Code only', detail: 'A browser connects only with a code you type into it.' },
+];
+
+/** How a browser with the extension gets in, kept by Browsentic Bridge in config.json; `browsentic pairing` changes the same setting. */
+function PairingSettings({ model, state }: { model: Model; state: State }) {
+ if (state.daemon !== 'on') return null;
+ return (
+ <Card>
+ <div className="space-y-3.5">
+ <SectionTitle title="Pairing" subtitle="How a browser with the extension connects to Browsentic Bridge. Browsers already paired stay paired." />
+ {state.pairingMode ? (
+ <div role="radiogroup" aria-label="Pairing" className="grid grid-cols-3 gap-2">
+ {PAIRING.map(({ mode, title, detail }) => {
+ const chosen = state.pairingMode === mode;
+ return (
+ <button
+ key={mode}
+ type="button"
+ role="radio"
+ aria-checked={chosen}
+ disabled={state.busy.includes('pairing')}
+ onClick={() => void model.setPairingMode(mode)}
+ className={cn(
+ 'space-y-1 rounded-xl border px-3.5 py-3 text-left transition-colors disabled:opacity-60',
+ chosen ? 'border-brand/50 bg-brand/10' : 'border-line bg-ground-2 hover:border-line-strong',
+ )}
+ >
+ <span className={cn('block text-[13px] font-semibold', chosen ? 'text-brand' : 'text-ink')}>{title}</span>
+ <span className="block text-[11.5px] leading-snug text-ink-dim">{detail}</span>
+ </button>
+ );
+ })}
+ </div>
+ ) : (
+ <div className="flex items-center gap-3.5">
+ <p className="min-w-0 flex-1 text-xs text-ink-dim">
+ This Browsentic Bridge started before browsers could connect by themselves, so it pairs only with a code. Restart it to choose.
+ </p>
+ <PrimaryButton onClick={() => void model.restartDaemon()}>Restart it</PrimaryButton>
+ </div>
+ )}
+ </div>
+ </Card>
+ );
+}
+
/** The settings every paired browser shares, kept by the daemon in config.json. The extension's own settings page edits the same values. */
function BrowserSettings({ model, state }: { model: Model; state: State }) {
if (state.daemon !== 'on') return <OfflineHint what="The browser theme and the guardrails" model={model} daemonOff={state.daemon === 'off'} />;