A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat(security): take privileged connector actions only from the app
Alan Buscaglia8ac11aa001a4
diff --git a/README.md b/README.mdindex 1d8ef57..6418fb3 100644--- a/README.md+++ b/README.md@@ -145,9 +145,9 @@ A small Node daemon starts the agent engine (Gentle Shell, `gentle-shell --mode## Security status-What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Credentials are typed in the app, never in the chat, and the assistant cannot read them with its file tools.+What already holds: computer control's grant, panic stop, blocklist, rate limit, and risky-action confirmations are enforced by the desktop app, not the agent, and the agent's processes do not inherit the app's macOS permissions. Connectors are reached only through the assistant's own proxy, which hides what their mode does not allow. Approving a connector's action and changing a connector (its mode, connecting, removing, importing) happen only in the desktop app that started the assistant, in native dialogs, over a private channel the agent cannot open; in the browser those controls are read-only. Credentials are typed in the app, never in the chat, and the assistant cannot read them with its file tools.-What does not yet: the agent has a shell, and its shell commands are checked on a best-effort basis only. Connector tokens live in files rather than the Keychain, and the approval cards travel over a channel the agent could reach. Moving connector traffic and approvals out of the agent's reach (a daemon-side MCP proxy with Keychain tokens and native approvals) is the next milestone before a stable release.+What does not yet: the agent has a shell, and its shell commands are checked on a best-effort basis only. Connector tokens live in files rather than the Keychain. Moving them to the Keychain, and protecting the connector settings file, are the next steps before a stable release.<div align="right"><a href="#top">Back to top</a></div>diff --git a/apps/desktop/src-tauri/Cargo.toml b/apps/desktop/src-tauri/Cargo.tomlindex 0c8f5cf..c733b8c 100644--- a/apps/desktop/src-tauri/Cargo.toml+++ b/apps/desktop/src-tauri/Cargo.toml@@ -43,7 +43,7 @@ block2 = "0.6"objc2-foundation = { version = "0.3", default-features = false, features = ["std", "block2", "NSArray", "NSDictionary", "NSError", "NSLocale", "NSNotification", "NSOperation", "NSSet", "NSString", "NSValue"] }objc2-core-foundation = { version = "0.3", default-features = false, features = ["std", "CFArray", "CFCGTypes", "CFData", "CFDictionary", "CFNumber", "CFString"] }objc2-core-graphics = { version = "0.3", default-features = false, features = ["std", "CGDataProvider", "CGDirectDisplay", "CGError", "CGEvent", "CGEventTypes", "CGImage", "CGRemoteOperation", "CGWindow"] }-objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "libc", "NSRunningApplication", "NSWorkspace"] }+objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "libc", "NSAlert", "NSApplication", "NSButton", "NSControl", "NSResponder", "NSRunningApplication", "NSView", "NSWorkspace"] }objc2-application-services = { version = "0.3", default-features = false, features = ["std", "libc", "AXError", "AXUIElement", "AXValue", "HIServices"] }objc2-screen-capture-kit = { version = "0.3", default-features = false, features = ["std", "block2", "libc", "objc2-core-foundation", "objc2-core-graphics", "SCScreenshotManager", "SCShareableContent", "SCStream"] }# Voice input (S30.1): the Speech framework, the audio engine, and the microphone permission.diff --git a/apps/desktop/src-tauri/build.rs b/apps/desktop/src-tauri/build.rsindex 171aba7..77e12ce 100644--- a/apps/desktop/src-tauri/build.rs+++ b/apps/desktop/src-tauri/build.rs@@ -26,6 +26,7 @@ const COMMANDS: &[&str] = &["voice_model_remove","shortcut_get","shortcut_set",+ "connector_command",];fn find_in_path(program: &str, path: &str) -> Option<PathBuf> {diff --git a/apps/desktop/src-tauri/capabilities/default.json b/apps/desktop/src-tauri/capabilities/default.jsonindex 7ec1899..3bcd2a0 100644--- a/apps/desktop/src-tauri/capabilities/default.json+++ b/apps/desktop/src-tauri/capabilities/default.json@@ -46,6 +46,12 @@"windows": ["panel"],"permissions": ["allow-shortcut-get", "allow-shortcut-set"]},+ {+ "identifier": "connectors",+ "description": "Connector changes from the panel (S25.2): sent to the daemon over the app's private channel on behalf of the panel's window; the Dot and the web page cannot make them.",+ "windows": ["panel"],+ "permissions": ["allow-connector-command"]+ },{"identifier": "glow","description": "What the computer-control glow overlay (S28) may call: listening to the glow and session events, nothing else.",diff --git a/apps/desktop/src-tauri/permissions/autogenerated/connector_command.toml b/apps/desktop/src-tauri/permissions/autogenerated/connector_command.tomlnew file mode 100644index 0000000..48bb293--- /dev/null+++ b/apps/desktop/src-tauri/permissions/autogenerated/connector_command.toml@@ -0,0 +1,11 @@+# Automatically generated - DO NOT EDIT!++[[permission]]+identifier = "allow-connector-command"+description = "Enables the connector_command command without any pre-configured scope."+commands.allow = ["connector_command"]++[[permission]]+identifier = "deny-connector-command"+description = "Denies the connector_command command without any pre-configured scope."+commands.deny = ["connector_command"]diff --git a/apps/desktop/src-tauri/src/alert.rs b/apps/desktop/src-tauri/src/alert.rsindex 331b9c2..f80d700 100644--- a/apps/desktop/src-tauri/src/alert.rs+++ b/apps/desktop/src-tauri/src/alert.rs@@ -1,10 +1,27 @@-//! Native yes/no alerts owned by the app (NSAlert through the dialog plugin on macOS), never the-//! webview, whose default button is the safe one (L75 A2). NSAlert makes the first button the-//! default (Return, highlighted, rightmost), so the refusing button goes first and only a click-//! on the allowing button allows. Escape, closing, or aborting the alert refuses too.+//! Native yes/no alerts owned by the app, never the webview, whose default button is the safe one+//! (L75 A2). Only a click on the allowing button allows: the refusing button, Return, Escape,+//! closing, aborting, an alert that cannot be shown, and any answer not recognized here refuse.+//!+//! macOS: an `NSAlert` run modally on the main thread, asked from a worker thread that waits for+//! the answer. The refusing button is added first (`NSAlertFirstButtonReturn`) with Return as its+//! key equivalent; the allowing button is second and has none, so no key allows. Only the second+//! button's response allows; `abortModal` (the approvals' stale-dialog dismissal) answers+//! `NSModalResponseAbort`, which refuses. The dialog plugin is not used there: with no parent window+//! rfd shows a `CFUserNotification` and reports cancels and failures as `Cancel`, which the plugin+//! turns into the second label of `OkCancelCustom` (T23c B1).+//!+//! Elsewhere (Linux): the dialog plugin with the allowing label in the OK slot and the refusing one+//! in the cancel slot, so every outcome rfd reports as `Cancel` (the refusing button, Escape,+//! closing, a dialog that failed) arrives as the refusing label. rfd's GTK dialog sets no default+//! response, so Return does not pick the allowing button either (not verified on a Linux desktop).use tauri::AppHandle;-use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind, MessageDialogResult};+use tauri_plugin_dialog::{MessageDialogButtons, MessageDialogResult};++/// The `NSAlert` response of the refusing button, added first (`NSAlertFirstButtonReturn`).+pub const REFUSE_RESPONSE: isize = 1000;+/// The `NSAlert` response of the allowing button, added second (`NSAlertSecondButtonReturn`).+pub const ALLOW_RESPONSE: isize = 1001;/// The two buttons of a yes/no alert.#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -14,27 +31,85 @@ pub struct Choice {}impl Choice {- /// The buttons in the plugin's order: the first one is the alert's default.+ /// The `NSAlert` buttons in the order they are added: the first is the default (Return).+ pub fn alert_buttons(&self) -> [&'static str; 2] {+ [self.refuse, self.allow]+ }++ /// True only for the allowing button's response; `None` is an alert that never ran.+ pub fn allows_response(&self, response: Option<isize>) -> bool {+ self.allow != self.refuse && response == Some(ALLOW_RESPONSE)+ }++ /// The plugin's buttons (off macOS): the refusing label takes the cancel slot, where rfd puts+ /// Escape, closing, and failures.pub fn buttons(&self) -> MessageDialogButtons {- MessageDialogButtons::OkCancelCustom(self.refuse.into(), self.allow.into())+ MessageDialogButtons::OkCancelCustom(self.allow.into(), self.refuse.into())}- /// True only when the allowing button was pressed.+ /// True only when the plugin reports the allowing button itself.pub fn allowed(&self, result: &MessageDialogResult) -> bool {self.allow != self.refuse && matches!(result, MessageDialogResult::Custom(label) if label == self.allow)}}-/// Shows the alert and waits for the answer. Blocks, so it never runs on the main thread.+/// Shows the alert and waits for the answer. Blocks, so it never runs on the main thread (there it+/// refuses at once).pub fn ask(app: &AppHandle, title: &str, message: &str, choice: Choice) -> bool {- let result = app- .dialog()- .message(message)- .title(title)- .kind(MessageDialogKind::Warning)- .buttons(choice.buttons())- .blocking_show_with_result();- choice.allowed(&result)+ #[cfg(target_os = "macos")]+ return macos::ask(app, title, message, choice);+ #[cfg(not(target_os = "macos"))]+ {+ use tauri_plugin_dialog::{DialogExt, MessageDialogKind};+ let result = app+ .dialog()+ .message(message)+ .title(title)+ .kind(MessageDialogKind::Warning)+ .buttons(choice.buttons())+ .blocking_show_with_result();+ choice.allowed(&result)+ }+}++#[cfg(target_os = "macos")]+mod macos {+ use super::Choice;+ use objc2_app_kit::{NSAlert, NSAlertStyle, NSApplication};+ use objc2_foundation::{MainThreadMarker, NSString};+ use tauri::AppHandle;++ pub fn ask(app: &AppHandle, title: &str, message: &str, choice: Choice) -> bool {+ if MainThreadMarker::new().is_some() {+ eprintln!("gentle-dot: a confirmation was asked on the main thread, so it was refused");+ return false;+ }+ let (answer, answered) = std::sync::mpsc::channel();+ let (title, message) = (title.to_owned(), message.to_owned());+ let scheduled = app.run_on_main_thread(move || {+ let response = MainThreadMarker::new().map(|mtm| run(mtm, &title, &message, choice));+ let _ = answer.send(response);+ });+ if scheduled.is_err() {+ return false;+ }+ // The task dropped without running (the app is quitting) reads as no answer.+ choice.allows_response(answered.recv().ok().flatten())+ }++ fn run(mtm: MainThreadMarker, title: &str, message: &str, choice: Choice) -> isize {+ let alert = NSAlert::new(mtm);+ alert.setAlertStyle(NSAlertStyle::Warning);+ alert.setMessageText(&NSString::from_str(title));+ alert.setInformativeText(&NSString::from_str(message));+ let [refuse, allow] = choice.alert_buttons();+ alert.addButtonWithTitle(&NSString::from_str(refuse)).setKeyEquivalent(&NSString::from_str("\r"));+ alert.addButtonWithTitle(&NSString::from_str(allow)).setKeyEquivalent(&NSString::from_str(""));+ // Gentle Dot is an accessory app; without this the alert can open behind the front app.+ #[allow(deprecated)]+ NSApplication::sharedApplication(mtm).activateIgnoringOtherApps(true);+ alert.runModal()+ }}#[cfg(test)]@@ -44,26 +119,61 @@ mod tests {const CHOICE: Choice = Choice { allow: "Allow", refuse: "Cancel" };#[test]- fn the_refusing_button_comes_first_so_it_is_the_default() {- match CHOICE.buttons() {- MessageDialogButtons::OkCancelCustom(first, second) => {- assert_eq!(first, "Cancel");- assert_eq!(second, "Allow");- }- other => panic!("unexpected buttons: {other:?}"),+ fn only_the_allowing_buttons_response_allows_an_alert() {+ assert!(CHOICE.allows_response(Some(ALLOW_RESPONSE)));+ // The refusing button (also Return), an aborted alert (a stale one dismissed after the+ // timeout), a stopped or cancelled modal session, an OK nobody can press, a button that+ // does not exist, and an alert that never ran: every one refuses.+ for response in [Some(REFUSE_RESPONSE), Some(-1001), Some(-1000), Some(0), Some(1), Some(1002), Some(-1), None] {+ assert!(!CHOICE.allows_response(response), "{response:?}");}+ let same = Choice { allow: "OK", refuse: "OK" };+ assert!(!same.allows_response(Some(ALLOW_RESPONSE)));}#[test]- fn only_the_allowing_button_allows() {- assert!(CHOICE.allowed(&MessageDialogResult::Custom("Allow".into())));- assert!(!CHOICE.allowed(&MessageDialogResult::Custom("Cancel".into())));- assert!(!CHOICE.allowed(&MessageDialogResult::Custom("allow".into())));- // Return on the default button, Escape, a closed or aborted alert.- assert!(!CHOICE.allowed(&MessageDialogResult::Ok));- assert!(!CHOICE.allowed(&MessageDialogResult::Yes));- assert!(!CHOICE.allowed(&MessageDialogResult::Cancel));- assert!(!CHOICE.allowed(&MessageDialogResult::No));+ fn the_refusing_button_is_added_first_so_it_is_the_default() {+ assert_eq!(CHOICE.alert_buttons(), ["Cancel", "Allow"]);+ assert_eq!((REFUSE_RESPONSE, ALLOW_RESPONSE), (1000, 1001));+ #[cfg(target_os = "macos")]+ {+ assert_eq!(REFUSE_RESPONSE, objc2_app_kit::NSAlertFirstButtonReturn);+ assert_eq!(ALLOW_RESPONSE, objc2_app_kit::NSAlertSecondButtonReturn);+ assert_eq!(objc2_app_kit::NSModalResponseAbort, -1001);+ }+ }++ /// What tauri-plugin-dialog 2.8.1 returns for `OkCancelCustom(ok, cancel)` (desktop.rs:227-252):+ /// rfd's `Ok` becomes `Custom(ok)`, rfd's `Cancel` (Cancel, Escape, closing, a dialog that failed)+ /// becomes `Custom(cancel)`, anything else passes through.+ fn plugin_result(rfd_ok: Option<bool>, buttons: &MessageDialogButtons) -> MessageDialogResult {+ match (rfd_ok, buttons) {+ (Some(true), MessageDialogButtons::OkCancelCustom(ok, _)) => MessageDialogResult::Custom(ok.clone()),+ (Some(false), MessageDialogButtons::OkCancelCustom(_, cancel)) => MessageDialogResult::Custom(cancel.clone()),+ (Some(true), _) => MessageDialogResult::Ok,+ _ => MessageDialogResult::Cancel,+ }+ }++ #[test]+ fn with_the_plugin_cancelling_closing_or_failing_refuses() {+ let buttons = CHOICE.buttons();+ assert!(matches!(&buttons, MessageDialogButtons::OkCancelCustom(ok, cancel) if ok == "Allow" && cancel == "Cancel"));+ // Only the allowing button.+ assert!(CHOICE.allowed(&plugin_result(Some(true), &buttons)));+ // The refusing button, Escape, closing, and failures all arrive as rfd's Cancel.+ assert!(!CHOICE.allowed(&plugin_result(Some(false), &buttons)));+ for result in [+ MessageDialogResult::Ok,+ MessageDialogResult::Cancel,+ MessageDialogResult::Yes,+ MessageDialogResult::No,+ MessageDialogResult::Custom("allow".into()),+ MessageDialogResult::Custom("Cancel".into()),+ MessageDialogResult::Custom(String::new()),+ ] {+ assert!(!CHOICE.allowed(&result), "{result:?}");+ }}#[test]diff --git a/apps/desktop/src-tauri/src/app_channel.rs b/apps/desktop/src-tauri/src/app_channel.rsnew file mode 100644index 0000000..4e0e1bc--- /dev/null+++ b/apps/desktop/src-tauri/src/app_channel.rs@@ -0,0 +1,403 @@+//! The private channel to the daemon this app launched (S25.1–S25.3). When the app spawns the+//! daemon it creates a connected pair of Unix sockets and hands one end to the daemon as fd 3+//! (`daemon::spawn_daemon`); it keeps the other. That connection is the authentication: nothing is+//! written to a file or an environment variable and nothing listens, so another process (the agent+//! included) cannot reach it. A daemon the app only attached to gets no channel.+//!+//! Frames are line-delimited JSON in both directions; each side numbers its own requests:+//! {"kind":"request","id":1,"method":"command","params":{"clientId":"…","message":{…}}}+//! {"kind":"response","id":1,"result":{}} or {"kind":"response","id":1,"error":"…"}+//! The app sends `command` (a privileged message from the panel, on behalf of its window),+//! `computer_register`, and `computer_unregister`. The daemon sends `approve` with an+//! [`ApprovalRequest`]; the app shows the native dialog on a worker thread (never the main thread)+//! and answers `{"approved": bool}`. A failed dialog, malformed request, or closed channel refuses.++use crate::approvals::ApprovalRequest;+use serde::{Deserialize, Serialize};+use serde_json::{json, Value};+use std::collections::HashMap;+use std::io::{self, BufRead, BufReader, Read, Write};+use std::net::Shutdown;+use std::os::unix::net::UnixStream;+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};+use std::sync::{mpsc, Arc, Mutex, PoisonError};+use std::time::Duration;++/// Where the daemon finds its end of the channel.+pub const APP_FD: i32 = 3;+/// A command may wait for a native confirmation (120 s) before the daemon answers.+pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(150);+/// Registering the computer helper waits for the daemon to start reading the channel.+pub const REGISTER_TIMEOUT: Duration = Duration::from_secs(60);+/// A frame longer than this closes the channel.+const MAX_FRAME: u64 = 1024 * 1024;++/// What the panel may ask the daemon through the app (S25.2): connector changes, approving a draft+/// (declining one any window may), and importing. The computer helper is registered by the app.+pub const PANEL_COMMANDS: &[&str] = &[+ "connector_connect",+ "connector_signin",+ "connector_setup",+ "connector_disconnect",+ "connector_remove",+ "connector_mode",+ "connector_draft_reply",+ "connector_import",+];++/// Why the panel cannot change connectors: the daemon was not started by this app.+pub const NO_CHANNEL: &str = "Gentle Dot did not start this assistant, so its connectors cannot be changed from here. \+Quit the assistant that is running and open Gentle Dot again.";++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(tag = "kind", rename_all = "snake_case")]+pub enum Frame {+ Request {+ id: u64,+ method: String,+ #[serde(default)]+ params: Value,+ },+ Response {+ id: u64,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ result: Option<Value>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ error: Option<String>,+ },+}++/// True for a panel message the app forwards: one of [`PANEL_COMMANDS`] with an object shape.+pub fn is_panel_command(message: &Value) -> bool {+ message.get("type").and_then(Value::as_str).is_some_and(|kind| PANEL_COMMANDS.contains(&kind))+}++/// What the app does for the daemon: native approvals, and setup once the channel is open.+pub trait Handler: Send + Sync {+ /// Shows the native dialog and blocks until the answer; true only when the user allowed it.+ fn approve(&self, request: &ApprovalRequest) -> bool;+ /// The channel to a freshly spawned daemon is open (for example, register the computer helper).+ fn opened(&self, _channel: &Arc<AppChannel>) {}+}++type Reply = mpsc::Sender<Result<Value, String>>;++pub struct AppChannel {+ writer: Mutex<UnixStream>,+ pending: Mutex<HashMap<u64, Reply>>,+ next: AtomicU64,+ open: AtomicBool,+}++impl AppChannel {+ /// Reads `stream` on a thread of its own; each daemon request runs on a worker thread.+ pub fn start(stream: UnixStream, handler: Arc<dyn Handler>) -> io::Result<Arc<Self>> {+ let reader = stream.try_clone()?;+ let channel = Arc::new(AppChannel {+ writer: Mutex::new(stream),+ pending: Mutex::new(HashMap::new()),+ next: AtomicU64::new(0),+ open: AtomicBool::new(true),+ });+ let reading = channel.clone();+ std::thread::Builder::new()+ .name("app-channel".into())+ .spawn(move || reading.read(BufReader::new(reader), handler))?;+ Ok(channel)+ }++ pub fn is_open(&self) -> bool {+ self.open.load(Ordering::SeqCst)+ }++ /// Sends a request and waits for its answer, the timeout, or the channel closing.+ pub fn request(&self, method: &str, params: Value, timeout: Duration) -> Result<Value, String> {+ if !self.is_open() {+ return Err("The assistant's channel is closed.".into());+ }+ let id = self.next.fetch_add(1, Ordering::SeqCst) + 1;+ let (reply, answer) = mpsc::channel();+ self.pending().insert(id, reply);+ if let Err(error) = self.write(&Frame::Request { id, method: method.into(), params }) {+ self.pending().remove(&id);+ return Err(format!("The assistant could not be reached: {error}"));+ }+ let result = answer.recv_timeout(timeout);+ self.pending().remove(&id);+ match result {+ Ok(answer) => answer,+ Err(mpsc::RecvTimeoutError::Timeout) => Err("The assistant did not answer in time.".into()),+ Err(mpsc::RecvTimeoutError::Disconnected) => Err("The assistant's channel is closed.".into()),+ }+ }++ /// A panel message on behalf of the window `client_id`; anything but [`PANEL_COMMANDS`] is refused here.+ pub fn command(&self, client_id: &str, message: Value) -> Result<(), String> {+ if !is_panel_command(&message) {+ return Err("Only connector changes go through the app.".into());+ }+ self.request("command", json!({"clientId": client_id, "message": message}), COMMAND_TIMEOUT).map(|_| ())+ }++ pub fn close(&self) {+ self.open.store(false, Ordering::SeqCst);+ let _ = self.writer.lock().unwrap_or_else(PoisonError::into_inner).shutdown(Shutdown::Both);+ // Dropping the senders wakes every waiting request.+ self.pending().clear();+ }++ fn pending(&self) -> std::sync::MutexGuard<'_, HashMap<u64, Reply>> {+ self.pending.lock().unwrap_or_else(PoisonError::into_inner)+ }++ fn write(&self, frame: &Frame) -> io::Result<()> {+ let mut line = serde_json::to_vec(frame).map_err(io::Error::other)?;+ line.push(b'\n');+ self.writer.lock().unwrap_or_else(PoisonError::into_inner).write_all(&line)+ }++ fn read(self: Arc<Self>, mut reader: BufReader<UnixStream>, handler: Arc<dyn Handler>) {+ let mut line = Vec::new();+ loop {+ line.clear();+ match (&mut reader).take(MAX_FRAME + 1).read_until(b'\n', &mut line) {+ Ok(0) | Err(_) => break,+ Ok(_) if line.last() != Some(&b'\n') => {+ eprintln!("gentle-dot: the assistant's channel sent a frame that is too long; closing it");+ break;+ }+ Ok(_) => {}+ }+ match serde_json::from_slice::<Frame>(&line) {+ Ok(Frame::Response { id, result, error }) => {+ if let Some(reply) = self.pending().remove(&id) {+ let _ = reply.send(match error {+ Some(error) => Err(error),+ None => Ok(result.unwrap_or(Value::Null)),+ });+ }+ }+ Ok(Frame::Request { id, method, params }) => {+ let (channel, handler) = (self.clone(), handler.clone());+ // A dialog blocks until the user answers: never on this thread or the main one.+ let spawned = std::thread::Builder::new()+ .name("app-channel-request".into())+ .spawn(move || channel.answer(id, &method, params, handler.as_ref()));+ if spawned.is_err() {+ let _ = self.write(&Frame::Response { id, result: None, error: Some("busy".into()) });+ }+ }+ Err(_) => eprintln!("gentle-dot: the assistant's channel sent a frame that is not understood"),+ }+ }+ self.close();+ }++ fn answer(&self, id: u64, method: &str, params: Value, handler: &dyn Handler) {+ let frame = match method {+ "approve" => {+ let approved = serde_json::from_value::<ApprovalRequest>(params).is_ok_and(|r| handler.approve(&r));+ Frame::Response { id, result: Some(json!({"approved": approved})), error: None }+ }+ other => Frame::Response { id, result: None, error: Some(format!("Unknown request: {other}")) },+ };+ let _ = self.write(&frame);+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::approvals::fake::{Answer, FakePrompt};+ use crate::approvals::{Approvals, Decision};+ use std::time::Instant;++ /// The daemon's side of the pair, read and written frame by frame.+ struct FakeDaemon {+ reader: BufReader<UnixStream>,+ writer: UnixStream,+ }++ impl FakeDaemon {+ fn next(&mut self) -> Frame {+ let mut line = String::new();+ self.reader.read_line(&mut line).unwrap();+ serde_json::from_str(&line).unwrap_or_else(|e| panic!("{e}: {line:?}"))+ }++ fn send(&mut self, frame: &Frame) {+ writeln!(self.writer, "{}", serde_json::to_string(frame).unwrap()).unwrap();+ }+ }++ #[derive(Default)]+ struct Recorder {+ asked: Mutex<Vec<ApprovalRequest>>,+ answer: AtomicBool,+ main_thread: AtomicBool,+ }++ impl Handler for Recorder {+ fn approve(&self, request: &ApprovalRequest) -> bool {+ if std::thread::current().name() == Some("main") {+ self.main_thread.store(true, Ordering::SeqCst);+ }+ self.asked.lock().unwrap().push(request.clone());+ self.answer.load(Ordering::SeqCst)+ }+ }++ fn pair(handler: Arc<dyn Handler>) -> (Arc<AppChannel>, FakeDaemon) {+ let (app, daemon) = UnixStream::pair().unwrap();+ let channel = AppChannel::start(app, handler).unwrap();+ let reader = BufReader::new(daemon.try_clone().unwrap());+ (channel, FakeDaemon { reader, writer: daemon })+ }++ #[test]+ fn frames_are_tagged_json_lines() {+ let request = Frame::Request { id: 1, method: "command".into(), params: json!({"clientId": "w"}) };+ assert_eq!(+ serde_json::to_value(&request).unwrap(),+ json!({"kind": "request", "id": 1, "method": "command", "params": {"clientId": "w"}})+ );+ let ok: Frame = serde_json::from_str(r#"{"kind":"response","id":2,"result":{}}"#).unwrap();+ assert_eq!(ok, Frame::Response { id: 2, result: Some(json!({})), error: None });+ let failed: Frame = serde_json::from_str(r#"{"kind":"response","id":3,"error":"no"}"#).unwrap();+ assert_eq!(failed, Frame::Response { id: 3, result: None, error: Some("no".into()) });+ }++ #[test]+ fn only_connector_changes_are_panel_commands() {+ for kind in PANEL_COMMANDS {+ assert!(is_panel_command(&json!({"type": kind})), "{kind}");+ }+ for kind in ["send", "ui_response", "computer_register", "computer_unregister", "connectors_list", "auth_reply"] {+ assert!(!is_panel_command(&json!({"type": kind})), "{kind}");+ }+ assert!(!is_panel_command(&json!("connector_mode")));+ assert!(!is_panel_command(&json!({"type": 1})));+ }++ #[test]+ fn a_command_goes_to_the_daemon_for_its_window_and_waits_for_the_answer() {+ let (channel, mut daemon) = pair(Arc::new(Recorder::default()));+ let message = json!({"type": "connector_mode", "connectorId": "notion", "mode": "read_write"});+ let sender = {+ let channel = channel.clone();+ let message = message.clone();+ std::thread::spawn(move || channel.command("window-1", message))+ };+ let Frame::Request { id, method, params } = daemon.next() else { panic!("not a request") };+ assert_eq!(method, "command");+ assert_eq!(params, json!({"clientId": "window-1", "message": message}));+ daemon.send(&Frame::Response { id, result: Some(json!({})), error: None });+ assert_eq!(sender.join().unwrap(), Ok(()));++ let refused = std::thread::spawn({+ let channel = channel.clone();+ move || channel.command("window-1", json!({"type": "connector_remove", "connectorId": "x"}))+ });+ let Frame::Request { id, .. } = daemon.next() else { panic!("not a request") };+ daemon.send(&Frame::Response { id, result: None, error: Some("That window is gone.".into()) });+ assert_eq!(refused.join().unwrap(), Err("That window is gone.".into()));+ }++ #[test]+ fn a_message_that_is_not_a_connector_change_never_leaves_the_app() {+ let (channel, daemon) = pair(Arc::new(Recorder::default()));+ let sent = channel.command("w", json!({"type": "computer_register", "url": "http://127.0.0.1:1/mcp", "token": "t"}));+ assert!(sent.is_err());+ assert!(channel.command("w", json!({"type": "send", "text": "hi"})).is_err());+ daemon.writer.set_nonblocking(true).unwrap();+ let mut buf = [0u8; 1];+ assert!(matches!((&daemon.writer).read(&mut buf), Err(e) if e.kind() == io::ErrorKind::WouldBlock));+ }++ #[test]+ fn the_daemon_asks_for_approvals_answered_off_the_main_thread() {+ let recorder = Arc::new(Recorder::default());+ let (_channel, mut daemon) = pair(recorder.clone());+ let request = json!({"connector": "Notion", "action": "create pages", "preview": [{"name": "title", "value": "Plan"}]});+ recorder.answer.store(true, Ordering::SeqCst);+ daemon.send(&Frame::Request { id: 7, method: "approve".into(), params: request.clone() });+ assert_eq!(daemon.next(), Frame::Response { id: 7, result: Some(json!({"approved": true})), error: None });+ recorder.answer.store(false, Ordering::SeqCst);+ daemon.send(&Frame::Request { id: 8, method: "approve".into(), params: request });+ assert_eq!(daemon.next(), Frame::Response { id: 8, result: Some(json!({"approved": false})), error: None });+ assert_eq!(recorder.asked.lock().unwrap()[0].connector, "Notion");+ assert!(!recorder.main_thread.load(Ordering::SeqCst));+ }++ #[test]+ fn a_malformed_approval_or_an_unknown_request_is_refused_without_asking() {+ let recorder = Arc::new(Recorder::default());+ recorder.answer.store(true, Ordering::SeqCst);+ let (_channel, mut daemon) = pair(recorder.clone());+ daemon.send(&Frame::Request { id: 1, method: "approve".into(), params: json!({"connector": 5}) });+ assert_eq!(daemon.next(), Frame::Response { id: 1, result: Some(json!({"approved": false})), error: None });+ daemon.send(&Frame::Request { id: 2, method: "open_everything".into(), params: json!({}) });+ assert!(matches!(daemon.next(), Frame::Response { id: 2, result: None, error: Some(_) }));+ assert!(recorder.asked.lock().unwrap().is_empty());+ }++ /// The approvals module behind the channel: one native dialog with the request's preview.+ struct Native(Approvals);++ impl Handler for Native {+ fn approve(&self, request: &ApprovalRequest) -> bool {+ self.0.confirm(request) == Decision::Approved+ }+ }++ #[test]+ fn approvals_reach_the_native_dialog_and_its_answer_goes_back() {+ let prompt = Arc::new(FakePrompt::new([Answer::After(Duration::ZERO, true), Answer::After(Duration::ZERO, false)]));+ let native = Native(Approvals::new(prompt.clone(), Duration::from_secs(5)));+ let (_channel, mut daemon) = pair(Arc::new(native));+ let request = json!({"connector": "Slack", "action": "send message", "preview": [{"name": "channel", "value": "#general"}]});+ daemon.send(&Frame::Request { id: 1, method: "approve".into(), params: request.clone() });+ assert_eq!(daemon.next(), Frame::Response { id: 1, result: Some(json!({"approved": true})), error: None });+ daemon.send(&Frame::Request { id: 2, method: "approve".into(), params: request });+ assert_eq!(daemon.next(), Frame::Response { id: 2, result: Some(json!({"approved": false})), error: None });+ assert_eq!(prompt.shown_titles(), ["Allow Slack to send message?", "Allow Slack to send message?"]);+ assert!(prompt.shown.lock().unwrap()[0].message.contains("channel: #general"));+ }++ #[test]+ fn a_request_without_an_answer_times_out() {+ let (channel, mut daemon) = pair(Arc::new(Recorder::default()));+ let started = Instant::now();+ let result = channel.request("computer_register", json!({}), Duration::from_millis(200));+ assert!(result.is_err());+ assert!(started.elapsed() >= Duration::from_millis(200));+ assert!(matches!(daemon.next(), Frame::Request { .. }));+ }++ #[test]+ fn when_the_daemon_goes_away_waiting_requests_fail_and_the_channel_is_closed() {+ let (channel, daemon) = pair(Arc::new(Recorder::default()));+ let waiting = std::thread::spawn({+ let channel = channel.clone();+ move || channel.request("computer_register", json!({}), Duration::from_secs(10))+ });+ std::thread::sleep(Duration::from_millis(100));+ drop(daemon);+ assert!(waiting.join().unwrap().is_err());+ let deadline = Instant::now() + Duration::from_secs(2);+ while channel.is_open() && Instant::now() < deadline {+ std::thread::sleep(Duration::from_millis(10));+ }+ assert!(!channel.is_open());+ assert!(channel.command("w", json!({"type": "connector_disconnect", "connectorId": "notion"})).is_err());+ }++ #[test]+ fn closing_the_channel_ends_the_daemons_side() {+ let (channel, mut daemon) = pair(Arc::new(Recorder::default()));+ channel.close();+ let mut line = String::new();+ assert_eq!(daemon.reader.read_line(&mut line).unwrap(), 0);+ assert!(!channel.is_open());+ }+}diff --git a/apps/desktop/src-tauri/src/approvals/mod.rs b/apps/desktop/src-tauri/src/approvals/mod.rsindex 341a76c..329b8fa 100644--- a/apps/desktop/src-tauri/src/approvals/mod.rs+++ b/apps/desktop/src-tauri/src/approvals/mod.rs@@ -8,7 +8,7 @@//! for it in tests.#[cfg(test)]-mod fake;+pub(crate) mod fake;pub mod native;use crate::alert::Choice;@@ -30,6 +30,9 @@ pub const PREVIEW_BUDGET: usize = 4000;pub const MIN_VALUE_LIMIT: usize = 80;/// The most characters of a connector, action, or field name.pub const NAME_LIMIT: usize = 60;+/// The most characters of a title or sentence the daemon gives for a change the user started.+pub const TITLE_LIMIT: usize = 120;+pub const SUMMARY_LIMIT: usize = 600;/// One argument of the action, in the order the daemon chose (key fields first).#[derive(Debug, Clone, PartialEq, Deserialize)]@@ -39,13 +42,20 @@ pub struct PreviewField {}/// What the daemon asks the user to approve.-#[derive(Debug, Clone, PartialEq, Deserialize)]+#[derive(Debug, Clone, Default, PartialEq, Deserialize)]pub struct ApprovalRequest {/// The connector's display name ("Notion").pub connector: String,/// What it will do ("create pages").pub action: String,pub preview: Vec<PreviewField>,+ /// For a change the user started in the panel (S25.3: "Let Notion read and send?"), instead of+ /// "Allow <connector> to <action>?".+ #[serde(default)]+ pub title: Option<String>,+ /// Instead of "The assistant wants to <action> in <connector>.".+ #[serde(default)]+ pub summary: Option<String>,}#[derive(Debug, Clone, Copy, PartialEq, Eq)]@@ -78,10 +88,18 @@ impl ApprovalDialog {}).collect();let details = if fields.is_empty() { "(no details)".to_owned() } else { fields.join("\n") };+ let title = match &request.title {+ Some(title) => clip(&sanitize(title, true), TITLE_LIMIT, 1),+ None => format!("Allow {connector} to {action}?"),+ };+ let sentence = match &request.summary {+ Some(summary) => clip(&sanitize(summary, true), SUMMARY_LIMIT, 1),+ None => format!("The assistant wants to {action} in {connector}."),+ };ApprovalDialog {- title: format!("Allow {connector} to {action}?"),+ title,message: format!(- "The assistant wants to {action} in {connector}.\n\n{details}\n\n\+ "{sentence}\n\n{details}\n\n\If you do not answer within {}, it is declined.",spell(timeout)),diff --git a/apps/desktop/src-tauri/src/approvals/native.rs b/apps/desktop/src-tauri/src/approvals/native.rsindex 53dd7ef..b12e5a2 100644--- a/apps/desktop/src-tauri/src/approvals/native.rs+++ b/apps/desktop/src-tauri/src/approvals/native.rs@@ -1,5 +1,5 @@-//! The real approval dialog: an alert shown by the app (NSAlert through the dialog plugin on-//! macOS, as computer control does, S24.3), "Decline" as the default button.+//! The real approval dialog: an alert shown by the app (an `NSAlert` on macOS, as computer control+//! does, S24.3), "Decline" as the default button.use super::{ApprovalDialog, Prompt, APPROVAL_CHOICE};use tauri::AppHandle;@@ -20,7 +20,8 @@ impl Prompt for NativePrompt {}/// macOS: aborts the modal alert on screen. `-[NSApplication abortModal]` is the one modal- /// call meant for other threads; the aborted alert reads as Decline. The approvals gate+ /// call meant for other threads; the aborted alert answers `NSModalResponseAbort`, which+ /// `alert` reads as Decline. The approvals gate/// guarantees no other approval dialog is up, but a computer-control dialog stacked on top/// would be aborted instead, which also refuses (fail closed). Elsewhere the stale dialog/// stays until the user answers, and that answer is ignored.diff --git a/apps/desktop/src-tauri/src/approvals/tests.rs b/apps/desktop/src-tauri/src/approvals/tests.rsindex a1206d8..26ceb25 100644--- a/apps/desktop/src-tauri/src/approvals/tests.rs+++ b/apps/desktop/src-tauri/src/approvals/tests.rs@@ -7,7 +7,7 @@ fn field(name: &str, value: serde_json::Value) -> PreviewField {}fn request(preview: Vec<PreviewField>) -> ApprovalRequest {- ApprovalRequest { connector: "Slack".into(), action: "send message".into(), preview }+ ApprovalRequest { connector: "Slack".into(), action: "send message".into(), preview, ..Default::default() }}fn approvals(prompt: &Arc<FakePrompt>, timeout: Duration) -> Approvals {@@ -90,6 +90,7 @@ fn names_are_one_line_and_short() {connector: format!("Evil\nAllow everything {}", "z".repeat(100)),action: "send\u{202e}".into(),preview: vec![field("a\nb", json!("v"))],+ ..Default::default()};let dialog = ApprovalDialog::new(&req, LONG);assert!(!dialog.title.contains('\n'), "{}", dialog.title);@@ -101,10 +102,7 @@ fn names_are_one_line_and_short() {#[test]fn the_approval_buttons_default_to_decline() {assert_eq!(APPROVAL_CHOICE, Choice { allow: "Allow", refuse: "Decline" });- match APPROVAL_CHOICE.buttons() {- tauri_plugin_dialog::MessageDialogButtons::OkCancelCustom(first, _) => assert_eq!(first, "Decline"),- other => panic!("unexpected buttons: {other:?}"),- }+ assert_eq!(APPROVAL_CHOICE.alert_buttons()[0], "Decline");}#[test]@@ -201,3 +199,40 @@ fn requests_read_the_daemon_json() {.unwrap();assert_eq!(request.preview[1], field("parent", json!({"page_id": "1"})));}++#[test]+fn a_change_the_user_started_has_its_own_title_and_sentence() {+ let request: ApprovalRequest = serde_json::from_value(json!({+ "connector": "Notion",+ "action": "read and send",+ "title": "Let Notion read and send?",+ "summary": "The assistant will be able to send, post, and change things in Notion.",+ "preview": [{"name": "Sends", "value": "Pages and comments."}]+ }))+ .unwrap();+ let dialog = ApprovalDialog::new(&request, Duration::from_secs(120));+ assert_eq!(dialog.title, "Let Notion read and send?");+ assert_eq!(+ dialog.message,+ "The assistant will be able to send, post, and change things in Notion.\n\n\+Sends: Pages and comments.\n\n\+If you do not answer within 2 minutes, it is declined."+ );+}++#[test]+fn a_given_title_and_sentence_are_made_safe_too() {+ let request = ApprovalRequest {+ connector: "Notion".into(),+ action: "connect".into(),+ title: Some(format!("Connect\nNotion\u{202e}? {}", "t".repeat(200))),+ summary: Some(format!("It reads\u{200b} Notion. {}", "s".repeat(2000))),+ preview: vec![],+ };+ let dialog = ApprovalDialog::new(&request, LONG);+ assert!(!dialog.title.contains('\n'), "{}", dialog.title);+ assert!(dialog.title.starts_with("Connect Notion\\u{202e}? ttt"), "{}", dialog.title);+ assert!(dialog.title.chars().count() < 160, "{}", dialog.title);+ assert!(dialog.message.starts_with("It reads\\u{200b} Notion. sss"), "{}", dialog.message);+ assert!(dialog.message.contains("more characters)"), "{}", dialog.message);+}diff --git a/apps/desktop/src-tauri/src/computer/app.rs b/apps/desktop/src-tauri/src/computer/app.rsindex 7f036c7..f74c2ac 100644--- a/apps/desktop/src-tauri/src/computer/app.rs+++ b/apps/desktop/src-tauri/src/computer/app.rs@@ -48,6 +48,14 @@ enum Overlay {Mark(super::glow::Mark),}+impl Computer {+ /// The helper's address and key for this launch, registered with the daemon over the app's+ /// channel (S24.7, L61); `None` off macOS or when the helper did not start.+ pub fn endpoint(&self) -> Option<Endpoint> {+ self.endpoint.clone()+ }+}+/// Creates the session and, on macOS, starts the MCP helper, the timeout watcher, and the/// glow overlay. Runs in the app's setup, on the main thread.pub fn start(app: &AppHandle) -> Computer {@@ -290,7 +298,7 @@ pub fn computer_status(computer: State<'_, Computer>) -> StateEvent {computer.control.status(SystemClock.now_ms())}-/// Dialogs shown by the app itself (NSAlert through the dialog plugin), never the webview.+/// Dialogs shown by the app itself (an `NSAlert`, see `alert`), never the webview.#[cfg(target_os = "macos")]struct NativeDialogs {app: AppHandle,@@ -340,12 +348,10 @@ for up to 1 hour. Stop and ⌥⇧Esc still work."#[test]fn every_computer_dialog_defaults_to_its_refusing_button() {- use tauri_plugin_dialog::MessageDialogButtons::OkCancelCustom;for choice in [GRANT_CHOICE, CONFIRM_CHOICE, YOLO_CHOICE] {- match choice.buttons() {- OkCancelCustom(first, second) => assert_eq!((first.as_str(), second.as_str()), (choice.refuse, choice.allow)),- other => panic!("unexpected buttons: {other:?}"),- }+ assert_eq!(choice.alert_buttons(), [choice.refuse, choice.allow]);+ assert!(!choice.allows_response(Some(crate::alert::REFUSE_RESPONSE)));+ assert!(!choice.allows_response(None));}}diff --git a/apps/desktop/src-tauri/src/daemon.rs b/apps/desktop/src-tauri/src/daemon.rsindex 75fa297..534e86b 100644--- a/apps/desktop/src-tauri/src/daemon.rs+++ b/apps/desktop/src-tauri/src/daemon.rs@@ -1,12 +1,17 @@-//! Attaches to a running daemon or spawns one, and stops what it spawned.+//! Attaches to a running daemon or spawns one, and stops what it spawned. A daemon it spawns gets+//! its end of the app's private channel on fd 3 (S25.1, `app_channel`); one it attached to gets none.+pub use crate::app_channel::APP_FD;+use crate::app_channel::{AppChannel, Handler};use crate::health::check_health;use std::fs::{self, File, OpenOptions};use std::io;+use std::os::fd::{BorrowedFd, FromRawFd, OwnedFd};use std::os::unix::fs::{DirBuilderExt, OpenOptionsExt, PermissionsExt};+use std::os::unix::net::UnixStream;use std::path::{Path, PathBuf};use std::process::{Child, ExitStatus};-use std::sync::Mutex;+use std::sync::{Arc, Mutex};use std::thread;use std::time::{Duration, Instant};@@ -104,25 +109,59 @@ impl ChildProcess for Child {}}-/// Starts the daemon with stdin from `/dev/null` and its output in `log`. On macOS the app-/// disclaims responsibility for it, so it never inherits the app's TCC grants (S24.1).+/// A connected pair of Unix sockets: the app's end, and the daemon's, numbered above [`APP_FD`] so+/// placing it on fd 3 in the child never collides with it. Both are close-on-exec here.+pub fn channel_pair() -> io::Result<(UnixStream, OwnedFd)> {+ let (app, daemon) = UnixStream::pair()?;+ let daemon = OwnedFd::from(daemon);+ use std::os::fd::AsRawFd;+ if daemon.as_raw_fd() > APP_FD {+ return Ok((app, daemon));+ }+ // SAFETY: duplicating a descriptor we own; the copy is owned by the returned OwnedFd.+ let copy = unsafe { libc::fcntl(daemon.as_raw_fd(), libc::F_DUPFD_CLOEXEC, APP_FD + 1) };+ if copy == -1 {+ return Err(io::Error::last_os_error());+ }+ // SAFETY: `copy` is a fresh descriptor nobody else owns.+ Ok((app, unsafe { OwnedFd::from_raw_fd(copy) }))+}++/// Starts the daemon with stdin from `/dev/null`, its output in `log`, and `channel` (from+/// [`channel_pair`]) on fd 3. On macOS the app disclaims responsibility for it, so it never+/// inherits the app's TCC grants (S24.1).#[cfg(target_os = "macos")]-fn spawn_daemon(spec: &LaunchSpec, log: File) -> io::Result<Box<dyn ChildProcess>> {- let child = crate::disclaimed::spawn_disclaimed(&spec.program, &spec.args, &spec.envs, &log)?;+fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -> io::Result<Box<dyn ChildProcess>> {+ let child = crate::disclaimed::spawn_disclaimed(&spec.program, &spec.args, &spec.envs, &log, channel)?;Ok(Box::new(child))}#[cfg(not(target_os = "macos"))]-fn spawn_daemon(spec: &LaunchSpec, log: File) -> io::Result<Box<dyn ChildProcess>> {+fn spawn_daemon(spec: &LaunchSpec, log: File, channel: Option<BorrowedFd<'_>>) -> io::Result<Box<dyn ChildProcess>> {+ use std::os::fd::AsRawFd;+ use std::os::unix::process::CommandExt;use std::process::{Command, Stdio};- let child = Command::new(&spec.program)+ let mut command = Command::new(&spec.program);+ command.args(&spec.args).envs(spec.envs.iter().map(|(k, v)| (k, v))).stdin(Stdio::null()).stdout(log.try_clone()?)- .stderr(log)- .spawn()?;- Ok(Box::new(child))+ .stderr(log);+ if let Some(fd) = channel.map(|fd| fd.as_raw_fd()) {+ // SAFETY: runs in the child between fork and exec and only calls dup2, which is+ // async-signal-safe. `fd` is above APP_FD (channel_pair), so dup2 makes a new fd 3+ // without close-on-exec, while the original closes at exec.+ unsafe {+ command.pre_exec(move || {+ if libc::dup2(fd, APP_FD) == -1 {+ return Err(io::Error::last_os_error());+ }+ Ok(())+ });+ }+ }+ Ok(Box::new(command.spawn()?))}/// Sends SIGTERM, waits up to `grace` for a clean exit, then kills.@@ -161,11 +200,37 @@ pub struct Daemon {data_dir: PathBuf,runtime_dir: Option<PathBuf>,child: Mutex<Option<Box<dyn ChildProcess>>>,+ /// The private channel to the daemon this app spawned; attached daemons have none.+ channel: Mutex<Option<Arc<AppChannel>>>,+ /// Serves the daemon's requests; without it no channel is made.+ handler: Option<Arc<dyn Handler>>,+ /// Replaces [`launch_spec`] (tests).+ launch: Option<LaunchSpec>,}impl Daemon {pub fn new(port: u16, data_dir: PathBuf, runtime_dir: Option<PathBuf>) -> Self {- Self { port, data_dir, runtime_dir, child: Mutex::new(None) }+ Self { port, data_dir, runtime_dir, child: Mutex::new(None), channel: Mutex::new(None), handler: None, launch: None }+ }++ /// Every daemon this app spawns gets a channel served by `handler`.+ pub fn with_channel(mut self, handler: Arc<dyn Handler>) -> Self {+ self.handler = Some(handler);+ self+ }++ #[cfg(test)]+ fn with_launch(mut self, spec: LaunchSpec) -> Self {+ self.launch = Some(spec);+ self+ }++ /// The channel to the daemon, only while one this app spawned runs and the channel is open.+ pub fn channel(&self) -> Option<Arc<AppChannel>> {+ if !self.owns_running() {+ return None;+ }+ self.channel.lock().unwrap().clone().filter(|channel| channel.is_open())}pub fn is_healthy(&self) -> bool {@@ -206,10 +271,30 @@ impl Daemon {return Ok(());}}- let spec = launch_spec(|key| std::env::var(key).ok(), cfg!(debug_assertions), self.runtime_dir.as_deref());+ let spec = self.launch.clone().unwrap_or_else(|| {+ launch_spec(|key| std::env::var(key).ok(), cfg!(debug_assertions), self.runtime_dir.as_deref())+ });let log = open_private_log(&self.data_dir).map_err(|e| format!("cannot open daemon.log: {e}"))?;- let child = spawn_daemon(&spec, log).map_err(|e| format!("cannot start {}: {e}", spec.program))?;+ let pair = match &self.handler {+ Some(_) => Some(channel_pair().map_err(|e| format!("cannot open the assistant's channel: {e}"))?),+ None => None,+ };+ let channel_end = pair.as_ref().map(|(_, daemon_end)| {+ use std::os::fd::AsFd;+ daemon_end.as_fd()+ });+ let child = spawn_daemon(&spec, log, channel_end).map_err(|e| format!("cannot start {}: {e}", spec.program))?;*slot = Some(child);+ // The daemon's end now lives only in the daemon.+ if let (Some((app_end, _)), Some(handler)) = (pair, &self.handler) {+ match AppChannel::start(app_end, handler.clone()) {+ Ok(channel) => {+ handler.opened(&channel);+ *self.channel.lock().unwrap() = Some(channel);+ }+ Err(error) => eprintln!("gentle-dot: cannot read the assistant's channel: {error}"),+ }+ }Ok(())}@@ -219,11 +304,15 @@ impl Daemon {slot.as_mut().is_some_and(|child| matches!(child.try_wait(), Ok(None)))}- /// Stops the daemon only if this app spawned it.+ /// Stops the daemon only if this app spawned it, and closes its channel.pub fn stop(&self) {- if let Some(mut child) = self.child.lock().unwrap().take() {+ let child = self.child.lock().unwrap().take();+ if let Some(mut child) = child {stop_child(child.as_mut(), STOP_GRACE);}+ if let Some(channel) = self.channel.lock().unwrap().take() {+ channel.close();+ }}/// Blocking: call off the main thread.@@ -242,6 +331,10 @@ impl Daemon {#[cfg(test)]mod tests {use super::*;+ use crate::app_channel::{AppChannel, Handler};+ use std::io::{BufRead, BufReader, Write};+ use std::os::fd::{AsFd, AsRawFd};+ use std::os::unix::net::UnixStream;use std::process::Command;fn env_of(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {@@ -385,6 +478,105 @@ mod tests {assert_eq!(fs::read_to_string(dir.join("daemon.log")).unwrap(), "old line\nnew line\n");}+ fn sh_spec(script: &str) -> LaunchSpec {+ LaunchSpec { program: "/bin/sh".into(), args: vec!["-c".into(), script.into()], envs: vec![] }+ }++ fn read_line(stream: &UnixStream) -> String {+ // macOS refuses socket options (EINVAL) once the other end has closed; reading still works.+ let _ = stream.set_read_timeout(Some(Duration::from_secs(5)));+ let mut line = String::new();+ BufReader::new(stream).read_line(&mut line).unwrap();+ line+ }++ #[test]+ fn the_daemon_gets_its_end_of_the_channel_on_fd_3() {+ let dir = scratch_dir("channel-fd");+ let (app, daemon_end) = channel_pair().unwrap();+ let script = "if [ -S /dev/fd/3 ]; then kind=socket; else kind=other; fi; \+IFS= read -r line <&3; printf '%s %s\\n' \"$kind\" \"$line\" >&3";+ let mut child = spawn_daemon(&sh_spec(script), open_private_log(&dir).unwrap(), Some(daemon_end.as_fd())).unwrap();+ drop(daemon_end);+ (&app).write_all(b"ping\n").unwrap();+ assert_eq!(read_line(&app), "socket ping\n");+ assert!(child.wait().unwrap().success());+ // Once the daemon is gone, nothing else holds the other end.+ assert_eq!(read_line(&app), "");+ }++ #[test]+ fn the_channel_end_is_never_one_the_daemon_could_clobber() {+ let (_app, daemon_end) = channel_pair().unwrap();+ assert!(daemon_end.as_raw_fd() > APP_FD, "{}", daemon_end.as_raw_fd());+ }++ #[cfg(target_os = "macos")]+ #[test]+ fn without_a_channel_fd_3_is_closed_in_the_daemon() {+ let dir = scratch_dir("channel-none");+ let script = "if [ -e /dev/fd/3 ]; then echo open; else echo none; fi";+ let mut child = spawn_daemon(&sh_spec(script), open_private_log(&dir).unwrap(), None).unwrap();+ assert!(child.wait().unwrap().success());+ assert_eq!(fs::read_to_string(dir.join("daemon.log")).unwrap(), "none\n");+ }++ #[derive(Default)]+ struct Opened(Mutex<usize>);++ impl Handler for Opened {+ fn approve(&self, _: &crate::approvals::ApprovalRequest) -> bool {+ false+ }++ fn opened(&self, _: &Arc<AppChannel>) {+ *self.0.lock().unwrap() += 1;+ }+ }++ /// A daemon stand-in that answers every request on fd 3 with `{"echo": <id>}`.+ const ECHO: &str = r#"while IFS= read -r line <&3; do+id=$(printf '%s' "$line" | sed -E 's/.*"id":([0-9]+).*/\1/')+printf '{"kind":"response","id":%s,"result":{"echo":%s}}\n' "$id" "$id" >&3+done"#;++ #[test]+ fn a_daemon_this_app_spawned_gets_a_channel_until_it_stops() {+ let handler = Arc::new(Opened::default());+ let daemon = Daemon::new(1, scratch_dir("channel-own"), None)+ .with_channel(handler.clone())+ .with_launch(sh_spec(ECHO));+ assert!(daemon.channel().is_none());+ daemon.spawn().unwrap();+ let channel = daemon.channel().expect("a channel to the spawned daemon");+ assert_eq!(*handler.0.lock().unwrap(), 1);+ let answer = channel.request("ping", serde_json::json!({}), Duration::from_secs(5)).unwrap();+ assert_eq!(answer, serde_json::json!({"echo": 1}));+ daemon.stop();+ assert!(daemon.channel().is_none());+ assert!(!channel.is_open());+ }++ #[test]+ fn a_daemon_the_app_only_attached_to_gets_no_channel() {+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();+ let port = listener.local_addr().unwrap().port();+ thread::spawn(move || {+ for mut stream in listener.incoming().flatten() {+ let mut buf = [0u8; 512];+ let _ = std::io::Read::read(&mut stream, &mut buf);+ let _ = stream.write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\n{}");+ }+ });+ let handler = Arc::new(Opened::default());+ let daemon = Daemon::new(port, scratch_dir("channel-attached"), None)+ .with_channel(handler.clone())+ .with_launch(sh_spec(ECHO));+ daemon.ensure_running(Duration::from_secs(5)).unwrap();+ assert!(daemon.channel().is_none());+ assert_eq!(*handler.0.lock().unwrap(), 0);+ }+#[test]fn stop_child_terminates_with_sigterm() {let mut child = Command::new("/bin/sleep").arg("30").spawn().unwrap();diff --git a/apps/desktop/src-tauri/src/disclaimed.rs b/apps/desktop/src-tauri/src/disclaimed.rsindex 7856c10..1002fe2 100644--- a/apps/desktop/src-tauri/src/disclaimed.rs+++ b/apps/desktop/src-tauri/src/disclaimed.rs@@ -10,7 +10,7 @@ use std::collections::BTreeMap;use std::ffi::{CString, OsStr, OsString};use std::fs::File;use std::io;-use std::os::fd::AsRawFd;+use std::os::fd::{AsRawFd, BorrowedFd};use std::os::unix::ffi::{OsStrExt, OsStringExt};use std::os::unix::process::ExitStatusExt;use std::path::PathBuf;@@ -120,13 +120,15 @@ impl Drop for FileActions {}/// Runs `program` with `args` and the app's environment plus `envs`, stdin from `/dev/null`,-/// and stdout and stderr appended to `log`. A program without a `/` is looked up in the-/// child's `PATH`. No other descriptor of the app reaches the child.+/// stdout and stderr appended to `log`, and `channel` (the daemon's end of the app channel,+/// numbered above 3) on fd 3. A program without a `/` is looked up in the child's `PATH`. No other+/// descriptor of the app reaches the child.pub fn spawn_disclaimed(program: &str,args: &[String],envs: &[(String, String)],log: &File,+ channel: Option<BorrowedFd<'_>>,) -> io::Result<DisclaimedChild> {let mut env: BTreeMap<OsString, OsString> = std::env::vars_os().collect();env.extend(envs.iter().map(|(k, v)| (OsString::from(k), OsString::from(v))));@@ -174,6 +176,10 @@ pub fn spawn_disclaimed(check(libc::posix_spawn_file_actions_addopen(&mut actions.0, 0, dev_null.as_ptr(), libc::O_RDONLY, 0))?;check(libc::posix_spawn_file_actions_adddup2(&mut actions.0, log.as_raw_fd(), 1))?;check(libc::posix_spawn_file_actions_adddup2(&mut actions.0, log.as_raw_fd(), 2))?;+ if let Some(channel) = channel {+ // Named here, so POSIX_SPAWN_CLOEXEC_DEFAULT keeps it open in the child, and only it.+ check(libc::posix_spawn_file_actions_adddup2(&mut actions.0, channel.as_raw_fd(), crate::daemon::APP_FD))?;+ }let mut pid: libc::pid_t = 0;check(libc::posix_spawn(@@ -212,13 +218,13 @@ mod tests {}fn sh(script: &str, envs: &[(String, String)], log: &File) -> DisclaimedChild {- spawn_disclaimed("/bin/sh", &["-c".into(), script.into()], envs, log).unwrap()+ spawn_disclaimed("/bin/sh", &["-c".into(), script.into()], envs, log, None).unwrap()}#[test]fn the_child_answers_for_itself() {let (_, log) = scratch_log("disclaim");- let mut child = spawn_disclaimed("/bin/sleep", &["30".into()], &[], &log).unwrap();+ let mut child = spawn_disclaimed("/bin/sleep", &["30".into()], &[], &log, None).unwrap();thread::sleep(Duration::from_millis(100));let pid = child.id() as libc::pid_t;// SAFETY: a read-only query about a live child.@@ -241,7 +247,7 @@ mod tests {fn a_bare_program_name_is_found_in_the_child_path() {let (path, log) = scratch_log("path");let envs = [("PATH".to_string(), "/usr/bin:/bin".to_string())];- let mut child = spawn_disclaimed("echo", &["found".into()], &envs, &log).unwrap();+ let mut child = spawn_disclaimed("echo", &["found".into()], &envs, &log, None).unwrap();assert!(child.wait().unwrap().success());assert_eq!(std::fs::read_to_string(path).unwrap(), "found\n");}@@ -269,7 +275,7 @@ mod tests {#[test]fn stop_child_terminates_then_kills_after_the_grace() {let (_, log) = scratch_log("stop");- let mut child = spawn_disclaimed("/bin/sleep", &["30".into()], &[], &log).unwrap();+ let mut child = spawn_disclaimed("/bin/sleep", &["30".into()], &[], &log, None).unwrap();stop_child(&mut child, Duration::from_secs(5));assert_eq!(child.try_wait().unwrap().and_then(|s| s.signal()), Some(libc::SIGTERM));let mut stubborn = sh("trap '' TERM; sleep 30", &[], &log);@@ -281,6 +287,6 @@ mod tests {#[test]fn a_missing_program_is_an_error() {let (_, log) = scratch_log("missing");- assert!(spawn_disclaimed("/nonexistent/gentle-dot-node", &[], &[], &log).is_err());+ assert!(spawn_disclaimed("/nonexistent/gentle-dot-node", &[], &[], &log, None).is_err());}}diff --git a/apps/desktop/src-tauri/src/lib.rs b/apps/desktop/src-tauri/src/lib.rsindex b1c0f21..ce18d00 100644--- a/apps/desktop/src-tauri/src/lib.rs+++ b/apps/desktop/src-tauri/src/lib.rs@@ -1,4 +1,5 @@pub mod alert;+pub mod app_channel;pub mod approvals;pub mod computer;pub mod config;diff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rsindex 8b2500d..ca1a904 100644--- a/apps/desktop/src-tauri/src/shell.rs+++ b/apps/desktop/src-tauri/src/shell.rs@@ -1,8 +1,11 @@//! Tauri wiring: windows, commands, tray menu, global shortcut, Dot snapping,//! hiding the rose, the full-screen panel, voice input, the shortcut chosen in Settings,-//! and the daemon lifecycle (design §9).+//! the daemon lifecycle (design §9), and the app's private channel to the daemon (S25.1–S25.3).+use crate::app_channel::{self, AppChannel, NO_CHANNEL, REGISTER_TIMEOUT};+use crate::approvals::{native::NativePrompt, ApprovalRequest, Approvals, Decision, APPROVAL_TIMEOUT};use crate::computer::app as computer;+use crate::computer::server::Endpoint;use crate::computer::session::Reason;use crate::config::{self, ConnectionInfo, DesktopConfig, DEFAULT_SHORTCUT};use crate::daemon::{self, Daemon, RestartOutcome};@@ -118,6 +121,46 @@ fn read_connection_info(config: &DesktopConfig) -> CommandResult<ConnectionInfo>Ok(config::connection_info(config.port, token.trim()))}+/// Serves the daemon's requests on the app channel: native approvals (S25.3), and registering the+/// computer helper with a daemon this app just spawned (S24.7, L61).+struct ChannelService {+ approvals: Approvals,+ computer: Option<Endpoint>,+}++impl app_channel::Handler for ChannelService {+ fn approve(&self, request: &ApprovalRequest) -> bool {+ self.approvals.confirm(request) == Decision::Approved+ }++ fn opened(&self, channel: &Arc<AppChannel>) {+ let Some(endpoint) = self.computer.clone() else {+ return;+ };+ let channel = channel.clone();+ thread::spawn(move || {+ let params = serde_json::json!({ "url": endpoint.url, "token": endpoint.token });+ if let Err(error) = channel.request("computer_register", params, REGISTER_TIMEOUT) {+ eprintln!("gentle-dot: computer control was not registered with the assistant: {error}");+ }+ });+ }+}++/// A connector change from the panel (S25.2), sent over the app's channel on behalf of the panel's+/// window (`client_id`, from its `ready`), so its sign-in steps reach that window. Waits for the+/// daemon, which may first confirm a widening change in a native dialog.+#[tauri::command]+async fn connector_command(app: AppHandle, client_id: String, message: serde_json::Value) -> CommandResult {+ let daemon = app.state::<Shell>().daemon.clone();+ tauri::async_runtime::spawn_blocking(move || {+ let channel = daemon.channel().ok_or_else(|| NO_CHANNEL.to_string())?;+ channel.command(&client_id, message)+ })+ .await+ .map_err(err)?+}+/// Waits until the daemon answers `/health`, then returns its URLs and token.#[tauri::command]async fn connection_info(app: AppHandle) -> CommandResult<ConnectionInfo> {@@ -706,6 +749,7 @@ pub fn run() {set_panel_fullscreen,shortcut_get,shortcut_set,+ connector_command,computer::computer_endpoint,computer::computer_permissions,computer::computer_request_permission,@@ -726,8 +770,17 @@ pub fn run() {app.set_activation_policy(tauri::ActivationPolicy::Accessory);let handle = app.handle().clone();+ // Computer control first: a daemon this app spawns gets the helper over its channel.+ let computer = computer::start(&handle);+ let service = ChannelService {+ approvals: Approvals::new(Arc::new(NativePrompt::new(handle.clone())), APPROVAL_TIMEOUT),+ computer: computer.endpoint(),+ };+ app.manage(computer);let runtime_dir = daemon::runtime_dir(|key| std::env::var(key).ok(), app.path().resource_dir().ok());- let daemon = Arc::new(Daemon::new(config.port, config.data_dir.clone(), runtime_dir));+ let daemon = Arc::new(+ Daemon::new(config.port, config.data_dir.clone(), runtime_dir).with_channel(Arc::new(service)),+ );let starter = daemon.clone();thread::spawn(move || {if let Err(error) = starter.ensure_running(DAEMON_START_TIMEOUT) {@@ -745,7 +798,6 @@ pub fn run() {full_screen: Mutex::new(None),shortcut: Mutex::new(None),});- app.manage(computer::start(&handle));let (voice_input, voice_model) = voice::start(&handle);app.manage(voice_input);app.manage(voice_model);@@ -834,11 +886,11 @@ mod tests {}#[test]- fn the_shortcut_commands_are_registered_and_granted_to_the_panel_only() {+ fn the_shortcut_and_connector_commands_are_registered_and_granted_to_the_panel_only() {let build = include_str!("../build.rs");let capabilities: serde_json::Value =serde_json::from_str(include_str!("../capabilities/default.json")).unwrap();- for command in ["shortcut_get", "shortcut_set"] {+ for command in ["shortcut_get", "shortcut_set", "connector_command"] {assert!(build.contains(&format!("\"{command}\",")), "{command} is missing from build.rs");let permission = format!("allow-{}", command.replace('_', "-"));let windows: Vec<&serde_json::Value> = capabilities["capabilities"]diff --git a/docs/design.md b/docs/design.mdindex 3635648..3770067 100644--- a/docs/design.md+++ b/docs/design.md@@ -141,10 +141,12 @@ Every daemon message carries `seq` (monotonic per connection) so the UI can dete- Drafts (S19): the approval guard registers `propose_connector({name, description, transport, command?, args?, url?, env_names?, needs_oauth?})`, with secrets by name only. Its result to the model is only "The user will review this connector in the app". The draft travels to the daemon as `ctx.ui.setStatus("gentle-dot:connector-draft", <json>)`: a fire-and-forget record on the engine's own RPC output, which only the daemon reads (the agent's commands cannot write to it, and no file, socket, or key is added that the agent could reach). A typed value (`${input:NAME}`) may only stand for an env value (or an http server's header): anywhere else (the command, its arguments, the URL) it would put the secret into the command line or an address the model chose, so the guard answers the model "Secrets can only go into environment variables." and sends nothing, and the daemon refuses such a draft as well. The daemon checks it (lengths, `https` or loopback URLs, env names, typed values), keeps the newest five (`MAX_CONNECTOR_DRAFTS`; the windows keep the same five and take the waiting list again after each `ready`), and shows every window a card (`connector_draft`) with the command or URL and the secret names. `connector_draft_reply` decides: declining forgets it; approving adds the server (`origin` "Drafted by the assistant"), turned on, read only with every tool hidden (`toolExposure {"*": "hidden"}`, no curated list, so in "Read and send" every call asks), then asks for each secret in the app and signs in when `needs_oauth`. The assistant still cannot write `mcp.json` or run `mcp add` (guard), so the card is the only way in. Residual, as for the rest of the state (S25): `connectors.json` edited while the daemon is not running is loaded at its next start, and it can now hold a server of the user's own (a command).- Import (S20, `packages/daemon/src/connector-import.ts`): "Import my MCP servers" (`connectors_scan`) reads, never writes, the configs below the user's home (`GENTLE_DOT_IMPORT_HOME` in tests): Claude Desktop (`Library/Application Support/Claude/` and `.config/Claude/claude_desktop_config.json`), Claude Code (`.claude.json` `mcpServers`, its `projects[*].mcpServers`, and each project's `.mcp.json`), Cursor (`.cursor/mcp.json`), VS Code (`User/mcp.json` with `servers` and `inputs`, macOS and Linux), Windsurf (`.codeium/windsurf/mcp_config.json`, `serverUrl`), OpenCode (`.config/opencode/opencode.json`, `mcp` with command arrays and `environment`), and Gentle Shell (`.gentle-shell/agent/mcp.json`). Each entry maps to the engine's schema: `${VAR}` (Claude Code), `${env:VAR}` (VS Code, Cursor, Windsurf), and `{env:VAR}` (OpenCode) become `${VAR}`; `${userHome}` becomes the home folder; a VS Code `${input:id}` becomes a value the user types after the import; everything else is a literal. SSE servers (`type: "sse"`, or an address ending in `/sse`) are listed as not importable. The list (`connector_imports`) shows the name, the source apps, the command or address (`summary`), and env and header names only; values stay in the daemon. The summary, also shown for a custom connector in the Connectors list, is masked by structure, not by a word list: an address (an argument or the server URL, any scheme) keeps its scheme, host, and path, loses its user and password and its fragment, shows its query keys with every value as `•••`, and masks long opaque path segments (20 or more letters, digits, `_`, or `-`, mixing digits or cases); the argument after `--header`/`-H`, the value of `--header=`, and any `Name: value` argument whose name looks like a credential (Authorization, Cookie, `*key*`, `*token*`, `*secret*`, and so on) keep only the name; the argument after a flag named like a credential (`/token|secret|key|pass|auth|cred|bearer/i`) and the value of `name=value` forms of the same are masked; known token prefixes (`ghp_`, `sk-`, `xoxb-`, `AKIA`, `glpat-`, and others) and long opaque words are masked. Values the engine resolves at start are noted before the import (`notes`): "Runs a command on your computer to get this value." for a leading `!` (the command is not shown), and "Reads the environment variable NAME." for `$NAME`/`${NAME}`. Duplicates (the same command without npm versions, or the same URL) of a connector the user has, or of a catalog entry, are marked and cannot be imported. `connector_import` copies the chosen entries with their values into the private state, read only with every tool hidden, and never touches the source files.- The daemon holds the approved connector state (each connector's `enabled` and `mode`) in memory. It reads `<dataDir>/connectors.json` once, when it starts; after that the state changes only through the Connectors screen. The daemon is the only writer of `connectors.json`, `<agentHome>/mcp.json`, and the sign-in home's `mcp.json`, all rendered from memory, atomically, mode 0600. The sign-in home's `mcp-auth.json` changes only while a sign-in command runs or when the proxy saves a refreshed token; any other change is put back to what those left (or the file is removed when there was none). The engine's policy (below) also comes from memory, never from the files. The files are watched (folder watches plus a check every second, because file events on macOS can be missed right after a watch starts), and they are also checked before every agent start and after every run. A change made by anything else is put back, a project `<workspace>/.pi/mcp.json` is removed (a `.pi` link loses the link, never its target), and every window gets "A change to your connectors was blocked." Residual: a change made to the files while the daemon is not running is loaded at its next start; stage 2 (S25) moves enforcement out of the files. Every server is `exposure: "direct"` (the assistant turns codemode off). Read only is enforced by the proxy (above); the sign-in home's `mcp.json` still carries `toolExposure: {"*": "hidden", <curated tool>: "direct"}` for read only, as the engine would read it.-- MCP proxy (S25.4, `packages/daemon/src/mcp-proxy.ts`): the engine's `<agentHome>/mcp.json` lists every connector as `{url: "http://127.0.0.1:<port>/mcp/<id>", headers: {Authorization: "Bearer <proxy key>"}, exposure: "direct", timeout: 300}` (plus `enabled: false` when turned off) and nothing else: no real address, token, environment, or command. The key is random, kept only in memory, and new for every engine launch; the proxy accepts it only in the `Authorization` header (401 otherwise, never from the address) and refuses any request with an `Origin`. It answers JSON-RPC 2.0 as plain `application/json` over POST, like the computer helper (GET is 405, notifications 202): `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, and `prompts/get`. Upstream, the daemon keeps one pi-mcp `McpClient` per connector, connected on first use: streamable HTTP for a remote server, with its headers and the stored sign-in (sent as a bearer token and refreshed after a 401 with the stored refresh token, never a new browser sign-in), or stdio for a server the daemon runs itself, with the engine's environment plus the server's values. A dropped connection is made again on the next request; turning a connector off, removing it, or changing its server or values closes it, and so does the daemon's shutdown. Every request reads the connector's state from the daemon's memory, so a mode change applies at once, without an engine restart (the engine still restarts to list newly allowed tools). Policy: `tools/list` shows in read only only the tools that declare `readOnlyHint: true` AND are on the curated list (the same `isReadOnlyTool` rule the guard uses), and every tool in "Read and send"; `tools/call` refuses a hidden or unknown tool with a JSON-RPC error however it is called, taking the annotations from the server's own list, never the caller; a sending action (any tool that is not read-only) is forwarded only after the user approves its preview (connector, tool, and every argument) on the ask card (`DotBridge.confirm`, same card as the engine's approvals; T23c moves it to the app's native dialog). Declining, an ask that cannot be shown (no window), an answer that is stopped, or a connector changed while the card was open refuses it with a JSON-RPC error that says nothing was sent. Resources and prompts are reads: they are shown in "Read and send", and in read only only for a connector with a curated read-only list (the catalog's); a server of the user's own in read only exposes no resources or prompts, like its tools. Errors from the server are passed on with their code and message; a refused sign-in says to sign in again in Connectors; anything else says the connector could not be reached (the log masks addresses).+- MCP proxy (S25.4, `packages/daemon/src/mcp-proxy.ts`): the engine's `<agentHome>/mcp.json` lists every connector as `{url: "http://127.0.0.1:<port>/mcp/<id>", headers: {Authorization: "Bearer <proxy key>"}, exposure: "direct", timeout: 300}` (plus `enabled: false` when turned off) and nothing else: no real address, token, environment, or command. The key is random, kept only in memory, and new for every engine launch; the proxy accepts it only in the `Authorization` header (401 otherwise, never from the address) and refuses any request with an `Origin`. It answers JSON-RPC 2.0 as plain `application/json` over POST, like the computer helper (GET is 405, notifications 202): `initialize`, `ping`, `tools/list`, `tools/call`, `resources/list`, `resources/read`, `resources/templates/list`, `prompts/list`, and `prompts/get`. Upstream, the daemon keeps one pi-mcp `McpClient` per connector, connected on first use: streamable HTTP for a remote server, with its headers and the stored sign-in (sent as a bearer token and refreshed after a 401 with the stored refresh token, never a new browser sign-in), or stdio for a server the daemon runs itself, with the engine's environment plus the server's values. A dropped connection is made again on the next request; turning a connector off, removing it, or changing its server or values closes it, and so does the daemon's shutdown. Every request reads the connector's state from the daemon's memory, so a mode change applies at once, without an engine restart (the engine still restarts to list newly allowed tools). Policy: `tools/list` shows in read only only the tools that declare `readOnlyHint: true` AND are on the curated list (the same `isReadOnlyTool` rule the guard uses), and every tool in "Read and send"; `tools/call` refuses a hidden or unknown tool with a JSON-RPC error however it is called, taking the annotations from the server's own list, never the caller; a sending action (any tool that is not read-only) is forwarded only after the user approves its preview (connector, action, and every argument, key fields first) in the desktop app's native dialog, asked over the app channel (below; `DotBridge.askInApp`); windows only show an informational card. Declining, no answer (the app declines after 120 s, the daemon gives up at 130 s), no app to ask, the app quitting while it asks, an answer that is stopped, or a connector changed while it was asked refuses it with a JSON-RPC error that says nothing was sent. Resources and prompts are reads: they are shown in "Read and send", and in read only only for a connector with a curated read-only list (the catalog's); a server of the user's own in read only exposes no resources or prompts, like its tools. Errors from the server are passed on with their code and message; a refused sign-in says to sign in again in Connectors; anything else says the connector could not be reached (the log masks addresses).- Sign-in home: the engine's `mcp login`/`mcp logout` read the server from `mcp.json`, so they run with `PI_CODING_AGENT_DIR=<data>/connector-signin` (0700), the daemon's own folder: its `mcp.json` (0600) holds the real servers in the engine's format, rendered from memory, and its `mcp-auth.json` (0600) the sign-ins in pi-mcp's OAuth state format, keyed `mcp__<id>|<url>`. The first start with the proxy moves `<agentHome>/mcp-auth.json` there once (the copy is read back before the old file is removed; a file that shows up there later is not taken over). T23d moves these secrets to the Keychain.- Sign-in runs the engine's own command line as a separate process, `node <pi-coding-agent>/dist/bundle/cli.js mcp login <id>`, with the agent's isolated environment and `PI_CODING_AGENT_DIR=<data>/connector-signin`. The daemon relays the printed authorization URL (`auth_event` `auth_url`) and offers a `manual_code` prompt: when the browser cannot reach this computer's loopback callback, the user pastes the address it ended on, and the daemon opens it locally only when its origin and path equal the authorization URL's `redirect_uri` and its `state` matches. Cancel stops the process by PID. Flow ids start with `connector-`, so `auth_reply` reaches the right flow; typed and printed text is never logged (URLs are masked).- Status: `needs_setup` while a typed value is missing; for servers that sign in with OAuth, `connected` when the sign-in home's `mcp-auth.json` holds tokens under `mcp__<id>|<url>` (the id with `-` as `_`, like the engine; token values are dropped while parsing) and `needs_signin` otherwise; `connected` for servers with a token or none; `error` after a failed sign-in.+- App channel (S25.1–S25.3, `packages/daemon/src/app-channel.ts`, `apps/desktop/src-tauri/src/app_channel.rs`): when the desktop app spawns the daemon it creates a connected pair of Unix sockets and puts one end on the daemon's fd 3 (posix_spawn `adddup2` on macOS, with `POSIX_SPAWN_CLOEXEC_DEFAULT` closing every other descriptor; a `pre_exec` `dup2` on Linux); it keeps the other. The connection is the authentication: nothing is written to a file or an environment variable, and nothing listens. The daemon (`cli.ts`) opens fd 3 before it spawns anything, only when it is a socket and not Node's own IPC channel, and first checks that a child spawned the daemon's way would not hold it (a probe child compares the socket's identity on its fd 3); if one would, it closes it and runs without a channel. On macOS, libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so the engine, stdio servers, and sign-in commands never get it (`app-channel-fd.test.ts`); Node cannot mark an inherited descriptor close-on-exec, which is why the probe checks rather than assumes. Frames are line-delimited JSON (`{"kind":"request","id","method","params"}`, `{"kind":"response","id","result"|"error"}`), each side numbering its own requests. The app sends `command {clientId, message}`, `computer_register {url, token}`, and `computer_unregister`; the daemon sends `approve` with `{connector, action, preview: [{name, value}], title?, summary?}` and gets `{approved}`. The app answers on a worker thread with T23b's `approvals` (one native dialog at a time, Decline the default, 120 s timeout); a malformed request, a dialog that fails, or the channel closing refuses.+- Privileged messages (S25.2, `APP_COMMANDS` in the protocol): `connector_connect`, `connector_signin`, `connector_setup`, `connector_disconnect`, `connector_remove`, `connector_mode`, `connector_draft_reply` approving, `connector_import`, `computer_register`, and `computer_unregister` are refused on the WebSocket (`error app_required`, "Open the Gentle Dot app to change connectors.") whoever sends them, the access key notwithstanding (L49). The desktop panel sends them with the `connector_command` Tauri command, which the app forwards over the channel with the panel's `clientId` (from `ready`; it only routes the sign-in steps and refusals to that window and authorizes nothing by itself). Every other message stays on the WebSocket: chat, history, accounts, profiles, models, uploads, `connectors_list`, `connectors_scan`, sign-in answers (`auth_reply`, owner-checked), and declining a draft. Changes that widen access are confirmed natively even though the app sent them: switching to "Read and send", connecting or setting up a connector that is off, approving a draft, and importing (each with what it adds); declining sends the window `error declined` and changes nothing. Narrowing (read only, disconnecting, removing) and signing in again need no dialog. Without a channel (an attached daemon, `pnpm dev`, the web, a VPS until T23h) these messages and every approval fail closed. Approvals the daemon asks show in every window as an `ask` with `method: "app"` ("Waiting for your answer in the Gentle Dot app."); `ui_response` to it is refused.- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): the tools of a connector the proxy fronts (`proxied` in the policy: turned on and set up) pass, since the proxy filters them and asks itself; a card here would ask twice. A turned-off connector is not in `proxied` or the approved list, so its tools stay blocked here as well. For any other connector tool: it runs without asking only when it declares `readOnlyHint: true` AND it is on the curated list. Anything else asks through `ctx.ui.confirm`: an ask card ("Allow Notion to create pages?") with every argument, key fields first, up to 8,000 characters (beyond that it says "(truncated, N more characters)"), shown in a scrollable block. It is blocked when declined, when no one can answer, or when the connector is "Read only". A server outside the policy is blocked; without a valid policy every connector call asks.- Credential and control files: `<agentHome>/auth.json`, `mcp-auth.json` (where it was before the proxy), `models.json` (it can hold API keys), `mcp.json`, the sign-in home `<dataDir>/connector-signin` with its `mcp.json` and `mcp-auth.json`, `<dataDir>/connectors.json`, `<dataDir>/token`, and the guard itself. The file tools (`read`, `write`, `edit`, `grep`, `find`, `ls`) are blocked on them by resolved path (any spelling, `@` prefix, case, symlink, or hard link), and `grep` also on any folder that contains one. Commands (`bash`) are blocked when, with quotes, backslashes, and string concatenation removed, they name one of those files (any case; a pattern such as `mcp-a*` counts), the data folder `.gentle-dot`, `PI_CODING_AGENT_DIR`, `security find-generic-password` (or other keychain reads), or `mcp add|login|logout|remove`. The command check is best effort, not a security boundary: the assistant runs as the user with a shell, so a command can always build a name the check does not see. The in-memory connector state above does not depend on it, and stage 2 (S25) moves tokens out of the engine's reach.- Stage 2 integrity (S25) must cover the user's own servers too. Today `connectors.json` is trusted when the daemon starts, so a file edited while the daemon is not running can add a custom or imported server that runs an arbitrary command, turn it on, claim any `origin` ("Imported from …", "Drafted by the assistant"), and carry env or header values that are not escaped (`!command`, `$NAME`), which the engine runs or expands at the next start. S25's integrity check (state the agent cannot write, or a signature it cannot forge) must cover every field of those entries: command, arguments, URL, env, headers, `enabled`, `mode`, and `origin`.@@ -170,7 +172,7 @@ The assistant can see the screen and operate apps through a built-in MCP server- S24.4 Guards: a fixed blocklist (Gentle Dot itself, System Settings, SecurityAgent, loginwindow, Keychain Access, password managers), 10 actions per second, and a native per-action confirmation for risky actions (send, pay, buy, delete, submit, confirm, transfer, and their Spanish equivalents, by Accessibility role and title, by `return` on a default button, or by the declared `intent`).- S24.5 Permissions: the app reports and requests Accessibility and Screen Recording (`computer_permissions`, `computer_request_permission {kind}`). The Connectors screen shows a built-in "Computer" entry with both statuses, Grant buttons, Check again, the note that debug builds lose the grants on every rebuild (macOS ties them to the code signature), and a note when the current model does not accept images (`ConnectorInfo.noImages`, from the model's `input` in the engine's `get_state` and `set_model` answers).- S24.6 Visible state: the app emits `computer://state {active, endsAt?, reason?}` (`computer_status` gives the current one). While active, the rose shows the "in control" state (`dot-in_control`, mood `control`: accent rim, steady traveling light) and the panel shows "Controlling your Mac · mm:ss left" with Stop (`computer_stop`).-- S24.7 Wiring: on every connection the desktop panel calls `computer_endpoint` and, when it returns `{url, token}`, sends `computer_register {url, token}` (the protocol accepts only `http://127.0.0.1:<port>/mcp` and a header-safe key). The daemon keeps the endpoint in memory, never in `connectors.json`, and renders `computer: {url, headers: {Authorization: "Bearer <key>"}, exposure: "direct"}` into `mcp.json`, then restarts the engine when idle. The guard's policy lists it under `builtin`, so its tools run without in-engine approval cards. It is removed on `computer_unregister` or when the window that registered it disconnects. The key is never logged or sent to a window: `connectors` lists only a built-in "Computer" entry (`builtin: true`) that the connector messages cannot change or remove, no saved or imported connector can take the name `computer`, and the import scan never offers the helper.+- S24.7 Wiring: the app registers its helper itself, over the app channel, right after it spawns the daemon (`computer_register {url, token}`; the daemon accepts only `http://127.0.0.1:<port>/mcp` and a header-safe key). A window cannot register, repoint, or remove it (L61 closed): the panel only calls `computer_endpoint` to know whether a helper exists. The daemon keeps the endpoint in memory, never in `connectors.json`, and renders `computer: {url, headers: {Authorization: "Bearer <key>"}, exposure: "direct"}` into `mcp.json`, then restarts the engine when idle. The guard's policy lists it under `builtin`, so its tools run without in-engine approval cards. It is removed on `computer_unregister` from the app or when the app's channel closes; windows coming and going do not touch it. A daemon the app only attached to has no channel, so it gets no helper. The key is never logged or sent to a window: `connectors` lists only a built-in "Computer" entry (`builtin: true`) that the connector messages cannot change or remove, no saved or imported connector can take the name `computer`, and the import scan never offers the helper.- S24.8 Speed: `batch {steps: [{tool, ...args}], intent?}` runs 1 to 20 steps of `click`, `move`, `drag`, `scroll`, `type`, `key`, `open_app`, or `wait` in one call and returns one screenshot. Each step takes the single tool's path (session and epoch, blocklist, risky confirmation, N1/N2 typing rules, coordinates mapped with the screenshot taken before the batch) and counts as one action for the rate limit; a full window delays the step instead of refusing it. Steps are 100 ms apart (1.5 s after `open_app`) so each step's guards read the screen the previous one left. The batch's `intent` applies to every step on top of the step's own. The first refused, declined, or failed step stops the batch; the error says which steps ran and comes with a fresh screenshot while the session lasts (none after Stop or panic). Malformed batches (empty, over 20, a nested `batch`, `screenshot`, `list_apps`, unknown tools, invalid arguments) run nothing. Actions settle 150 ms before their screenshot (`open_app` 1.5 s); screenshots are JPEG quality 65; debug builds optimize `image`, `zune-*`, and this crate (opt-level 1, because the generic encoder is compiled here).- S24.9 Yolo mode: in memory only, off at launch. `computer_set_yolo {enabled}` and the tray item "Yolo mode" switch it; turning it on asks a native confirmation ("Turn on yolo mode? Gentle Dot will send, pay, delete, and submit without asking you first, for up to 1 hour. Stop and ⌥⇧Esc still work.", Turn On / Cancel). While on, only the risky-action confirmation is skipped; the grant, blocklist, rate limit, Stop, and panic are unchanged, and Stop or panic end the session, not yolo mode. It turns itself off after 1 hour. `computer://state` and `computer_status` add `yolo` and `yoloEndsAt?`; every switch reports the resulting state, so a declined confirmation flips the UI switch back. Connectors → Computer shows a "Yolo mode" switch, the banner shows "Yolo", and the rose carries a yellow mark (`dot-yolo`).- S28 The pink glow where the agent acts:@@ -283,7 +285,7 @@ The user changes the main assistant's model from the chat, in the panel and the- The daemon binds `127.0.0.1` only. A random 256-bit token is stored in `~/.gentle-dot/token` (mode 0600). The desktop app reads it; the browser receives it once by URL fragment.- WebSocket upgrades check `Origin` against an allowlist (`http://127.0.0.1:4317`, `tauri://localhost`).- The VPS guide requires HTTPS, a reverse proxy with authentication, and a dedicated Docker container with no access to personal machines.-- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Still open: the sign-ins are files in the daemon's sign-in home (Keychain in T23d), approval answers still come over the WebSocket (native dialogs and the app key in T23b/T23c), and the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.+- The assistant's engine runs as the user with a shell. Its file tools cannot read the token, sign-ins, or connector files, and the connector state lives in the daemon's memory (§4, Connectors), but shell checks are best effort: a determined command can still read what the user's account can read. Stage 2 (S25) moves connector tokens and enforcement into the daemon: the MCP proxy (S25.4, done) keeps every token, real address, and server environment out of the engine's `mcp.json`, and enforces mode, hidden tools, and approvals in the daemon. Connector changes and approvals come only from the desktop app that launched the daemon, over its private channel, and are answered in native dialogs (§4, App channel); the WebSocket's access key no longer reaches them. Still open: the sign-ins are files in the daemon's sign-in home (Keychain in T23d), Linux children could inherit the channel if libuv there does not close it (the daemon then refuses it; T23g), and the proxy key is in the engine's `mcp.json`, so the agent's shell could call the proxy directly; that reaches only what the proxy allows, and every sending action still needs the user's approval.## 9. Desktop shell contract (Tauri 2 <-> UI)@@ -312,6 +314,7 @@ When the panel opens, it is placed next to the Dot on the side with more room, a| `set_panel_fullscreen` | `{ "on": boolean }` | fills the work area of the panel's display, or restores the frame before; returns the resulting state || `shortcut_get` (panel only) | — | `{ "shortcut": "Alt+Space", "default": "Alt+Space" }`: the shortcut that toggles the panel now, in its normal spelling || `shortcut_set` (panel only) | `{ "shortcut": string }` | `{ "shortcut": string }` as saved, or a rejection with a reason for the user (see "Menu bar and shortcut") |+| `connector_command` (panel only) | `{ "clientId": string, "message": ClientMessage }` | sends a connector change (S25.2) to the daemon over the app channel on behalf of the window `clientId`; resolves once the daemon handled it (after any native confirmation), or rejects with a reason (no channel: the app did not start this daemon) |The Dot drags with `getCurrentWindow().startDragging()` (permission `core:window:allow-start-dragging`). After a drag ends (no move events for 300 ms), Rust snaps the Dot, by its real window size, to the nearest monitor edge with a 12 px margin and saves the position in `~/.gentle-dot/desktop.json`; the next launch restores it, or defaults to the right edge, vertically centered.@@ -356,7 +359,7 @@ The app is single-instance (`tauri-plugin-single-instance`; D-Bus on Linux). A s### Daemon lifecycle-On launch, the app checks `GET /health`. If the daemon does not answer, the app spawns it: `<node> <repo>/packages/daemon/src/cli.ts`, with the `PATH` captured at build time (apps launched from Finder get a minimal `PATH`, and the daemon needs `gentle-shell`). `build.rs` records the absolute `node` path, the daemon script path, and `PATH`; `GENTLE_DOT_NODE` and `GENTLE_DOT_DAEMON_SCRIPT` override them at runtime. A daemon spawned by the app is stopped on Quit. Restart assistant restarts a spawned daemon, and reports through a dialog when the daemon was started outside the app. The UI connects only after `/health` answers.+On launch, the app checks `GET /health`. If the daemon does not answer, the app spawns it: `<node> <repo>/packages/daemon/src/cli.ts`, with the `PATH` captured at build time (apps launched from Finder get a minimal `PATH`, and the daemon needs `gentle-shell`). `build.rs` records the absolute `node` path, the daemon script path, and `PATH`; `GENTLE_DOT_NODE` and `GENTLE_DOT_DAEMON_SCRIPT` override them at runtime. A daemon spawned by the app gets the app channel on fd 3 (§4); one the app attached to does not, so its connectors cannot be changed from the panel. A daemon spawned by the app is stopped on Quit, which also closes the channel. Restart assistant restarts a spawned daemon, and reports through a dialog when the daemon was started outside the app. The UI connects only after `/health` answers.## 10. Configurationdiff --git a/packages/daemon/src/app-channel.ts b/packages/daemon/src/app-channel.tsnew file mode 100644index 0000000..9308ace--- /dev/null+++ b/packages/daemon/src/app-channel.ts@@ -0,0 +1,250 @@+/**+ * The desktop app's private channel (S25.1–S25.3, docs/design.md "Security"). The app that launches+ * the daemon creates a connected pair of Unix sockets and hands one end to the daemon as fd 3. That+ * connection is the authentication: nothing is written to a file or an environment variable, and+ * there is no listening socket another process could reach. A daemon the app only attached to, one+ * started from a terminal, and the web have no channel, so privileged actions fail closed there.+ *+ * Frames are line-delimited JSON, in both directions:+ * {"kind":"request","id":1,"method":"command","params":{...}}+ * {"kind":"response","id":1,"result":{...}} or {"kind":"response","id":1,"error":"..."}+ * Each side numbers its own requests. The app sends `command` (a privileged message on behalf of a+ * window), `computer_register`, and `computer_unregister`; the daemon sends `approve` (a native+ * dialog, answered `{approved}`).+ */+import { type StdioOptions, spawnSync } from "node:child_process";+import { closeSync, fstatSync } from "node:fs";+import { Socket } from "node:net";+import type { Duplex } from "node:stream";++/** Where the app puts its end of the channel. */+export const APP_FD = 3;+/** Longer than the app's own 120 s dialog timeout, which answers "declined" first. */+export const APPROVAL_WAIT_MS = 130_000;+/** A frame longer than this closes the channel; nothing legitimate comes close. */+const MAX_FRAME = 1024 * 1024;++/** One argument of the action, in the order shown. */+export interface PreviewField {+ name: string;+ value: unknown;+}++/** What the app shows in its native dialog (apps/desktop approvals::ApprovalRequest). */+export interface AppApproval {+ /** The connector's name, as the user knows it. */+ connector: string;+ /** What it will do ("create pages"). */+ action: string;+ preview: PreviewField[];+ /** Replaces "Allow <connector> to <action>?" for a change the user started (S25.3). */+ title?: string;+ /** Replaces "The assistant wants to <action> in <connector>.". */+ summary?: string;+}++/** The app as the bridge sees it: whether it is there, and its native approvals. */+export interface AppLink {+ readonly connected: boolean;+ /** True only when the user allowed it; declined, unanswered, or the app gone resolve false. */+ approve(request: AppApproval, signal?: AbortSignal): Promise<boolean>;+}++type Frame =+ | { kind: "request"; id: number; method: string; params?: unknown }+ | { kind: "response"; id: number; result?: unknown; error?: string };++type Pending = { resolve(value: unknown): void; reject(error: Error): void; timer: NodeJS.Timeout };++export interface AppChannelOptions {+ log?: (line: string) => void;+ /** How long an approval waits for the app's answer. Default {@link APPROVAL_WAIT_MS}. */+ approvalWaitMs?: number;+}++export class AppChannel implements AppLink {+ /** Answers the app's requests; a thrown error goes back as the response's `error`. */+ handler: (method: string, params: unknown) => unknown = () => {+ throw new Error("The assistant is not ready yet.");+ };+ private readonly stream: Duplex;+ private readonly options: AppChannelOptions;+ private readonly pending = new Map<number, Pending>();+ private readonly closeListeners = new Set<() => void>();+ private buffer = "";+ private nextId = 0;+ private open = true;++ constructor(stream: Duplex, options: AppChannelOptions = {}) {+ this.stream = stream;+ this.options = options;+ stream.setEncoding("utf8");+ stream.on("data", (chunk: string) => this.receive(chunk));+ stream.on("end", () => this.close());+ stream.on("close", () => this.close());+ stream.on("error", (error: Error) => {+ this.log(`the app's channel failed: ${error.message}`);+ this.close();+ });+ }++ get connected(): boolean {+ return this.open;+ }++ /** Calls `listener` once when the channel closes (the app quit, or it was closed here). */+ onClose(listener: () => void): () => void {+ if (!this.open) {+ listener();+ return () => {};+ }+ this.closeListeners.add(listener);+ return () => this.closeListeners.delete(listener);+ }++ request(method: string, params: unknown, timeoutMs: number): Promise<unknown> {+ if (!this.open) return Promise.reject(new Error("The Gentle Dot app is not connected."));+ const id = ++this.nextId;+ return new Promise((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pending.delete(id);+ reject(new Error(`The Gentle Dot app did not answer ${method} in time.`));+ }, timeoutMs);+ this.pending.set(id, { resolve, reject, timer });+ this.write({ kind: "request", id, method, params });+ });+ }++ /** Rejects when there is no app to ask; every other failure is a refusal (fail closed). */+ approve(request: AppApproval, signal?: AbortSignal): Promise<boolean> {+ if (!this.open) return Promise.reject(new Error("The Gentle Dot app is not connected."));+ if (signal?.aborted) return Promise.resolve(false);+ const answer = this.request("approve", request, this.options.approvalWaitMs ?? APPROVAL_WAIT_MS).then(+ (result) => (result as { approved?: unknown } | undefined)?.approved === true,+ () => false,+ );+ if (!signal) return answer;+ const aborted = new Promise<boolean>((resolve) =>+ signal.addEventListener("abort", () => resolve(false), { once: true }),+ );+ return Promise.race([answer, aborted]);+ }++ close(): void {+ if (!this.open) return;+ this.open = false;+ this.stream.destroy();+ for (const [id, waiting] of this.pending) {+ clearTimeout(waiting.timer);+ waiting.reject(new Error("The Gentle Dot app closed its channel."));+ this.pending.delete(id);+ }+ for (const listener of [...this.closeListeners]) listener();+ this.closeListeners.clear();+ }++ private receive(chunk: string): void {+ this.buffer += chunk;+ for (let end = this.buffer.indexOf("\n"); end >= 0; end = this.buffer.indexOf("\n")) {+ const line = this.buffer.slice(0, end);+ this.buffer = this.buffer.slice(end + 1);+ if (line.trim() !== "") this.onFrame(line);+ if (!this.open) return;+ }+ if (this.buffer.length > MAX_FRAME) {+ this.log("the app's channel sent a frame that is too long; closing it");+ this.close();+ }+ }++ private onFrame(line: string): void {+ let frame: Frame;+ try {+ frame = JSON.parse(line) as Frame;+ } catch {+ this.log("the app's channel sent a frame that is not JSON; ignored");+ return;+ }+ if (typeof frame !== "object" || frame === null || typeof frame.id !== "number") return;+ if (frame.kind === "response") {+ const waiting = this.pending.get(frame.id);+ if (!waiting) return;+ this.pending.delete(frame.id);+ clearTimeout(waiting.timer);+ if (typeof frame.error === "string") waiting.reject(new Error(frame.error));+ else waiting.resolve(frame.result);+ return;+ }+ if (frame.kind !== "request" || typeof frame.method !== "string") return;+ const { id, method } = frame;+ Promise.resolve()+ .then(() => this.handler(method, frame.params))+ .then(+ (result) => this.write({ kind: "response", id, result: result ?? {} }),+ (error: Error) => this.write({ kind: "response", id, error: error.message }),+ );+ }++ private write(frame: Frame): void {+ if (this.open) this.stream.write(`${JSON.stringify(frame)}\n`);+ }++ private log(line: string): void {+ this.options.log?.(line);+ }+}++/**+ * True when a child spawned the way the daemon spawns its children would hold the socket `identity`+ * (`dev:ino`) on `fd`. Node offers no way to mark an inherited descriptor close-on-exec; on macOS+ * libuv spawns with `POSIX_SPAWN_CLOEXEC_DEFAULT`, so children get only their stdio. This checks+ * that instead of assuming it.+ */+export function childInherits(+ fd: number,+ identity: string,+ stdio: StdioOptions = ["ignore", "pipe", "ignore"],+) {+ const script = `try{const s=require("fs").fstatSync(${fd},{bigint:true});process.stdout.write(s.dev+":"+s.ino)}catch{}`;+ const probe = spawnSync(process.execPath, ["-e", script], { stdio, encoding: "utf8", timeout: 10_000 });+ // A probe that could not run proves nothing: treat it as a leak.+ if (probe.error || probe.status !== 0) return true;+ return probe.stdout === identity;+}++export interface InheritedChannelOptions extends AppChannelOptions {+ fd?: number;+ /** Tests replace the inheritance check. */+ probe?: (fd: number, identity: string) => boolean;+}++/**+ * The socket the app handed over on fd 3, or undefined when there is none (it is not a socket, or it+ * is Node's own IPC channel). When a child would inherit it, it is closed and refused: an agent+ * holding it could act as the app.+ */+export function inheritedAppSocket(options: InheritedChannelOptions = {}): Socket | undefined {+ const fd = options.fd ?? APP_FD;+ if (process.env.NODE_CHANNEL_FD === String(fd)) return undefined;+ let identity: string;+ try {+ const stat = fstatSync(fd, { bigint: true });+ if (!stat.isSocket()) return undefined;+ identity = `${stat.dev}:${stat.ino}`;+ } catch {+ return undefined;+ }+ const inherits = options.probe ?? childInherits;+ if (inherits(fd, identity)) {+ options.log?.("the app's channel was refused: children would inherit it; connectors cannot be changed");+ closeSync(fd);+ return undefined;+ }+ return new Socket({ fd, readable: true, writable: true });+}++/** {@link inheritedAppSocket} as a channel. */+export function openInheritedChannel(options: InheritedChannelOptions = {}): AppChannel | undefined {+ const socket = inheritedAppSocket(options);+ return socket ? new AppChannel(socket, options) : undefined;+}diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex 793a031..5c85735 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -1,19 +1,25 @@-import { randomUUID } from "node:crypto";+import { randomBytes, randomUUID } from "node:crypto";import { join } from "node:path";import {type AgentState,+ APP_REQUIRED,type Ask,type ClientMessage,+ type ConnectorDraft,+ type ConnectorInfo,type Features,+ isAppCommand,isThinkingLevel,type MessageQueue,type ModelGroup,type ModelRef,+ parseClientMessage,parseQueue,type RoleRoute,type ServerPayload,type VoiceCapability,} from "@gentle-dot/protocol";+import type { AppApproval, AppLink } from "./app-channel.ts";import type { AuthManager } from "./auth.ts";import type { ConnectorManager, ConnectorRefusal } from "./connectors.ts";import {@@ -54,6 +60,11 @@ export interface BridgeOptions {voice?: VoiceService;/** Files the user uploaded for their messages (S31). */uploads?: UploadStore;+ /**+ * The desktop app that launched the daemon, over its private channel (S25.1): the only source of+ * connector changes and the only place approvals are answered. Without it they fail closed.+ */+ app?: AppLink;/** How long switching conversations waits for a running answer to stop. Default 10 s. */stopTimeoutMs?: number;/** Optional parts of the app; by default one continuous chat. */@@ -79,16 +90,17 @@ type ProfileCommand = Extract<>;const DIALOG_METHODS = new Set(["select", "confirm", "input", "editor"]);+const WAITING_IN_APP = "Waiting for your answer in the Gentle Dot app.";+const DECLINED = { code: "declined", message: "Nothing was changed." } as const;/**- * An open dialog; `options` keeps the agent's original option strings for the answer. `settle` is set- * for the daemon's own questions (the MCP proxy's approvals): the answer goes there, not to the agent.+ * An open dialog; `options` keeps the agent's original option strings for the answer. An `app` ask+ * only shows that the desktop app is asking; windows cannot answer it.*/type PendingAsk = {ask: Ask;options?: string[];timer?: NodeJS.Timeout;- settle?: (allowed: boolean) => void;};const REMEMBERED_REQUEST_IDS = 500;const READY_TIMEOUT_MS = 60_000;@@ -102,6 +114,8 @@ const HISTORY_PAGE = 100;*/export class DotBridge {private readonly clients = new Set<BridgeClient>();+ /** Each window's id, for the app's commands on its behalf. */+ private readonly clientIds = new Map<string, BridgeClient>();private readonly asks = new Map<string, PendingAsk>();private readonly runningTools = new Set<string>();private readonly seenRequestIds: string[] = [];@@ -156,34 +170,34 @@ export class DotBridge {}/**- * Asks every window to confirm an action of the daemon's own (a connector's sending action through- * the MCP proxy), on the same card as the engine's approvals. Resolves true only when the user- * confirms; declining, stopping the answer, or `signal` resolves false. Rejects when no window can- * answer. T23c moves this to the desktop app's native dialog.+ * Asks the user in the desktop app's native dialog (S25.3); windows only see that it waits there.+ * Resolves true only when the user allows it; declining, no answer, `signal`, or the app quitting+ * resolve false. Rejects when there is no app to ask (fail closed).*/- confirm(title: string, message: string, signal?: AbortSignal): Promise<boolean> {- if (this.clients.size === 0) return Promise.reject(new Error("no window can answer"));- if (signal?.aborted) return Promise.resolve(false);- const requestId = `daemon-${randomUUID()}`;- return new Promise((resolve) => {- const ask: Ask = {- requestId,- method: "confirm",- title: presentText(title),- message: presentText(message),- };- this.asks.set(requestId, { ask, settle: resolve });- signal?.addEventListener("abort", () => this.resolveAsk(requestId), { once: true });- this.broadcast({ type: "ask", ask });- this.refreshState();- });+ askInApp(request: AppApproval, signal?: AbortSignal): Promise<boolean> {+ const app = this.options.app;+ if (!app?.connected) return Promise.reject(new Error(APP_REQUIRED));+ const requestId = `app-${randomUUID()}`;+ const ask: Ask = {+ requestId,+ method: "app",+ title: presentText(request.title ?? `Allow ${request.connector} to ${request.action}?`),+ message: WAITING_IN_APP,+ };+ this.asks.set(requestId, { ask });+ this.broadcast({ type: "ask", ask });+ this.refreshState();+ return app.approve(request, signal).finally(() => this.resolveAsk(requestId));}attach(client: BridgeClient): () => void {this.clients.add(client);+ const clientId = randomBytes(18).toString("base64url");+ this.clientIds.set(clientId, client);this.deliver(client, {type: "ready",agentState: this.state,+ clientId,...this.conversationRef(),...(this.supervisor.model ? { model: this.supervisor.model } : {}),features: this.features,@@ -196,13 +210,35 @@ export class DotBridge {if (this.interrupted) this.deliver(client, { type: "interrupted" });return () => {this.clients.delete(client);+ this.clientIds.delete(clientId);this.options.auth?.cancelOwnedBy(client);this.options.connectors?.cancelOwnedBy(client);- this.options.connectors?.unregisterComputer(client);};}+ /** A window's message. Connector changes come only from the desktop app (S25.2). */async handle(client: BridgeClient, message: ClientMessage): Promise<void> {+ if (isAppCommand(message)) {+ this.deliver(client, { type: "error", code: "app_required", message: APP_REQUIRED });+ return;+ }+ await this.run(client, message);+ }++ /**+ * A connector change from the desktop app's channel, on behalf of the window with `clientId`: its+ * sign-in steps and refusals go to that window. Throws when there is no such window or it is not+ * an app command.+ */+ async handleFromApp(clientId: string, raw: unknown): Promise<void> {+ const client = this.clientIds.get(clientId);+ if (!client) throw new Error("That window is not connected to the assistant any more.");+ const message = parseClientMessage(JSON.stringify(raw ?? null));+ if (!message || !isAppCommand(message)) throw new Error("Only connector changes come from the app.");+ await this.run(client, message);+ }++ private async run(client: BridgeClient, message: ClientMessage): Promise<void> {try {await this.dispatch(client, message);} catch (error) {@@ -294,9 +330,8 @@ export class DotBridge {return;}const { requestId } = message;- if (pending.settle) {- pending.settle(message.confirmed === true && !message.cancelled);- this.resolveAsk(requestId);+ if (pending.ask.method === "app") {+ this.deliver(client, { type: "error", code: "app_required", message: WAITING_IN_APP });return;}const answer: Record<string, unknown> = {};@@ -422,6 +457,8 @@ export class DotBridge {case "connector_draft_reply": {const emit = (payload: ServerPayload) => this.deliver(client, payload);const { draftId, approve } = message;+ const draft = this.options.connectors?.drafts().find((d) => d.draftId === draftId);+ if (approve && draft && !(await this.confirmChange(client, draftApproval(draft)))) return;const refused = this.requireConnectors().decideDraft(client, draftId, approve, emit);if (refused) this.deliver(client, { type: "error", ...refused });else this.broadcast({ type: "connector_draft_resolved", draftId, approved: approve });@@ -436,12 +473,13 @@ export class DotBridge {case "computer_unregister":this.requireConnectors().unregisterComputer(client);return;- case "connector_import":- this.deliver(client, {- type: "connector_imported",- names: this.requireConnectors().importServers(message.ids),- });+ case "connector_import": {+ const connectors = this.requireConnectors();+ const chosen = connectors.importChoices(message.ids);+ if (chosen.length > 0 && !(await this.confirmChange(client, importApproval(chosen)))) return;+ this.deliver(client, { type: "connector_imported", names: connectors.importServers(message.ids) });return;+ }case "profile_save":case "profile_rename":case "profile_duplicate":@@ -610,6 +648,8 @@ export class DotBridge {): Promise<void> {const connectors = this.requireConnectors();const emit = (payload: ServerPayload) => this.deliver(client, payload);+ const widening = wideningApproval(connectors.list(), message);+ if (widening && !(await this.confirmChange(client, widening))) return;let refused: ConnectorRefusal | undefined;switch (message.type) {case "connector_connect":@@ -634,6 +674,20 @@ export class DotBridge {if (refused) this.deliver(client, { type: "error", ...refused });}+ /**+ * A change that widens what the assistant can reach, confirmed in the app's native dialog even+ * though the app sent it (S25.3). False, with a note for the window, when it was not allowed.+ */+ private async confirmChange(client: BridgeClient, request: AppApproval): Promise<boolean> {+ const allowed = await this.askInApp(request).catch(() => undefined);+ if (allowed === undefined) {+ this.deliver(client, { type: "error", code: "app_required", message: APP_REQUIRED });+ return false;+ }+ if (!allowed) this.deliver(client, { type: "error", ...DECLINED });+ return allowed;+ }+/*** A connector the assistant drafted with `propose_connector`. It reaches the daemon on the* engine's own output, and every window shows it as a card; nothing changes until the user answers.@@ -1136,8 +1190,6 @@ export class DotBridge {const entry = this.asks.get(requestId);if (!entry) return;clearTimeout(entry.timer);- // A question of the daemon's that closes unanswered is a refusal (its answer, if any, came first).- entry.settle?.(false);this.asks.delete(requestId);this.broadcast({ type: "ask_resolved", requestId });this.refreshState();@@ -1197,3 +1249,66 @@ function queuedText(message: string): string {const names = `📎 ${attachments.map((a) => a.name).join(", ")}`;return text ? `${text}\n${names}` : names;}++/**+ * The native confirmation for a connector change that widens access, or undefined when it narrows+ * or keeps it (read only, disconnecting, removing, signing in again) or the connector is unknown.+ */+function wideningApproval(+ list: ConnectorInfo[],+ message: Extract<ClientMessage, { connectorId: string }>,+): AppApproval | undefined {+ const info = list.find((c) => c.id === message.connectorId && !c.builtin);+ if (!info) return undefined;+ const name = info.name;+ if (message.type === "connector_mode") {+ if (message.mode !== "read_write" || info.mode === "read_write") return undefined;+ return {+ connector: name,+ action: "read and send",+ title: `Let ${name} read and send?`,+ summary: `The assistant will be able to send, post, and change things in ${name}. It still asks you before each sending action.`,+ preview: [{ name: "Sends", value: info.sends }],+ };+ }+ if ((message.type === "connector_connect" || message.type === "connector_setup") && !info.enabled) {+ return {+ connector: name,+ action: "connect",+ title: `Connect ${name}?`,+ summary: `The assistant will be able to read ${name}. It starts read only.`,+ preview: [{ name: "Reads", value: info.reads }],+ };+ }+ return undefined;+}++/** Approving a connector the assistant drafted: everything that will run or be reached. */+function draftApproval(draft: ConnectorDraft): AppApproval {+ const preview: AppApproval["preview"] = [+ draft.transport === "http"+ ? { name: "Address", value: draft.url ?? "" }+ : { name: "Runs on this computer", value: [draft.command, ...(draft.args ?? [])].join(" ") },+ { name: "Secrets it needs", value: draft.envNames.length > 0 ? draft.envNames.join(", ") : "None" },+ ];+ if (draft.description) preview.unshift({ name: "What it does", value: draft.description });+ return {+ connector: draft.name,+ action: "be added",+ title: `Add ${draft.name}?`,+ summary: "The assistant drafted this connector. It starts read only, with all of its tools hidden.",+ preview,+ };+}++/** Importing servers from the user's other apps: each one by name and what it runs. */+function importApproval(chosen: { name: string; summary?: string }[]): AppApproval {+ const count = chosen.length;+ return {+ connector: count === 1 ? (chosen[0]?.name ?? "1 server") : `${count} servers`,+ action: "be imported",+ title: `Import ${count} server${count === 1 ? "" : "s"}?`,+ summary: "They start read only, with all of their tools hidden.",+ preview: chosen.map((c) => ({ name: c.name, value: c.summary ?? "" })),+ };+}diff --git a/packages/daemon/src/cli.ts b/packages/daemon/src/cli.tsindex 798d8df..fe4a5b5 100644--- a/packages/daemon/src/cli.ts+++ b/packages/daemon/src/cli.ts@@ -1,6 +1,7 @@#!/usr/bin/env nodeimport { existsSync } from "node:fs";import { fileURLToPath } from "node:url";+import { inheritedAppSocket } from "./app-channel.ts";import { loadConfig } from "./config.ts";import { APPROVAL_GUARD, bundledMcpCli } from "./connectors.ts";import { startDaemon, startupMessage } from "./daemon.ts";@@ -33,6 +34,9 @@ function selfCheck(): void {async function main(): Promise<void> {const config = loadConfig();+ // The desktop app that launched the daemon hands over its private channel on fd 3 (S25.1); it is+ // opened before anything is spawned, and refused if children would inherit it.+ const appChannel = inheritedAppSocket({ log });const daemon = await startDaemon({port: config.port,host: config.host,@@ -44,6 +48,7 @@ async function main(): Promise<void> {agentArgs: config.agentArgs,...(config.agentHome ? { agentHome: config.agentHome } : {}),allowedOrigins: config.allowedOrigins,+ ...(appChannel ? { appChannel } : {}),log,});process.stdout.write(`${startupMessage(daemon.url, config.dataDir, process.stdout.isTTY === true)}\n`);diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsindex fb5883c..261c21f 100644--- a/packages/daemon/src/connectors.ts+++ b/packages/daemon/src/connectors.ts@@ -877,17 +877,30 @@ export class ConnectorStore {}/**- * Before the proxy, the engine kept the sign-ins in its home. They move once, the first time the- * sign-in home is made: the copy is read back before the old file is removed. A file that shows up- * in the engine's home later is never taken over.+ * Before the proxy, the engine kept the sign-ins in its home. Whenever that file is there it is+ * moved: verbatim when the daemon holds no sign-ins yet, otherwise only the sign-ins the daemon+ * does not hold (its own always win, so a file planted later never replaces one). The result is+ * read back before the old file is removed, so a move that stopped halfway finishes next time.*/private moveLegacySignIns(): void {- if (existsSync(this.signinHome)) return;ensurePrivateDir(this.signinHome);const text = readOrUndefined(this.legacyAuthFile);if (text === undefined) return;- writePrivate(this.authFile, text);- if (readOrUndefined(this.authFile) !== text) {+ const legacy = signInStates(text);+ const currentText = readOrUndefined(this.authFile);+ const current = currentText === undefined ? {} : signInStates(currentText);+ if (!legacy || !current) {+ this.options.log?.("could not read the connector sign-ins to move; they stay where they were");+ return;+ }+ const missing = Object.keys(legacy).filter((key) => !(key in current));+ if (currentText === undefined) writePrivate(this.authFile, text);+ else if (missing.length > 0) {+ const merged = { ...Object.fromEntries(missing.map((key) => [key, legacy[key]])), ...current };+ writePrivate(this.authFile, `${JSON.stringify(merged, null, 2)}\n`);+ }+ const moved = signInStates(readOrUndefined(this.authFile) ?? "");+ if (!moved || Object.keys(legacy).some((key) => !(key in moved))) {this.options.log?.("could not move the connector sign-ins; they stay where they were");return;}@@ -1013,6 +1026,18 @@ function authKey(id: string, url: string): string {return `mcp__${id.replace(/-/g, "_")}|${new URL(url).href}`;}+/** The sign-ins of an `mcp-auth.json` by key; undefined when it is not a JSON object. */+function signInStates(text: string): Record<string, unknown> | undefined {+ try {+ const value = JSON.parse(text) as unknown;+ return typeof value === "object" && value !== null && !Array.isArray(value)+ ? (value as Record<string, unknown>)+ : undefined;+ } catch {+ return undefined;+ }+}+function readOrUndefined(path: string): string | undefined {try {return readFileSync(path, "utf8");@@ -1425,6 +1450,15 @@ export class ConnectorManager {return [...groups.values()].map(({ candidate }) => candidate);}+ /** The scanned servers `importServers(ids)` would add, by name and what they run; nothing changes. */+ importChoices(ids: string[]): { name: string; summary: string }[] {+ return ids.flatMap((key) => {+ const found = this.scanned.get(key);+ if (!found?.server || this.duplicateOf(found.server)) return [];+ return [{ name: found.name, summary: summarize(found.server) }];+ });+ }+/** Copies the chosen servers from the last scan, with their values, read only with every tool hidden. */importServers(ids: string[]): string[] {const imported: string[] = [];diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex 739a13e..3fc20b5 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -3,6 +3,7 @@ import { chmodSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSyncimport { createServer, type IncomingMessage, type ServerResponse } from "node:http";import type { AddressInfo } from "node:net";import { extname, join, resolve, sep } from "node:path";+import type { Duplex } from "node:stream";import type { McpTransport } from "@earendil-works/pi-mcp";import {type AttachmentLimits,@@ -12,6 +13,7 @@ import {parseClientMessage,} from "@gentle-dot/protocol";import { type WebSocket, WebSocketServer } from "ws";+import { AppChannel } from "./app-channel.ts";import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHome } from "./auth.ts";import { type BridgeClient, DotBridge } from "./bridge.ts";import {@@ -22,7 +24,7 @@ import {type McpCli,policyEnv,} from "./connectors.ts";-import { approvalCard } from "./extensions/approval-guard.ts";+import { approvalRequest } from "./extensions/approval-guard.ts";import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv, privateMemory } from "./isolation.ts";import { MCP_PREFIX, McpProxy, type ProxiedConnector, type UpstreamCredentials } from "./mcp-proxy.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";@@ -60,6 +62,13 @@ export interface DaemonOptions {importHome?: string;/** The connection the MCP proxy makes to a connector's real server; tests pass a stand-in. */connectorTransport?: (connector: ProxiedConnector, credentials: UpstreamCredentials) => McpTransport;+ /**+ * The desktop app's end of its private channel (fd 3 when the app launched the daemon, S25.1).+ * Without it, connector changes and approvals fail closed.+ */+ appChannel?: Duplex;+ /** How long an approval waits for the app's answer; default 130 s (the app declines at 120 s). */+ approvalWaitMs?: number;/** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */allowedOrigins?: string[];backoffMs?: number[];@@ -156,11 +165,12 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {const proxy = new McpProxy({connector: (id) => connectorStore.proxyView(id),credentials: (id) => connectorStore.credentials(id),- // For now on the same card path as the engine's approvals; T23c moves it to the app's native dialog.- approve: (preview, signal) => {- const card = approvalCard(preview.connector, preview.connectorId, preview.tool, preview.arguments);- return bridge.confirm(card.title, card.message, signal);- },+ // In the desktop app's native dialog, outside the agent's reach (S25.3).+ approve: (preview, signal) =>+ bridge.askInApp(+ approvalRequest(preview.connector, preview.connectorId, preview.tool, preview.arguments),+ signal,+ ),...(options.connectorTransport ? { transport: options.connectorTransport } : {}),env: agentEnv,cwd: options.workspace,@@ -223,6 +233,12 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {...(options.uploadLimits ? { limits: options.uploadLimits } : {}),});const historyPage = options.historyPage ?? Number(process.env.GENTLE_DOT_HISTORY_PAGE);+ const app = options.appChannel+ ? new AppChannel(options.appChannel, {+ log,+ ...(options.approvalWaitMs ? { approvalWaitMs: options.approvalWaitMs } : {}),+ })+ : undefined;const bridge = new DotBridge(supervisor, {dataDir: options.dataDir,log,@@ -231,11 +247,21 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {connectors,voice,uploads,+ ...(app ? { app } : {}),features: { conversations: options.conversations ?? process.env.GENTLE_DOT_CONVERSATIONS === "1" },rotation: options.rotation ?? rotationLimits(process.env),...(Number.isInteger(historyPage) && historyPage > 0 ? { historyPage } : {}),});+ if (app) {+ app.handler = (method, params) => appRequest(method, params, bridge, connectors, app);+ // The computer helper belongs to the app that registered it (S24.7).+ app.onClose(() => {+ log("the desktop app's channel closed");+ connectors.unregisterComputer(app);+ });+ } else log("no desktop app channel: connector changes and approvals are refused");+// The files as the daemon writes them (an older version kept a hash), then watched.connectorStore.enforce(false);connectorStore.watch();@@ -279,6 +305,7 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {bridge,supervisor,async close() {+ app?.close();for (const client of wss.clients) client.terminate();wss.close();// Stops waiting approvals and the connectors' servers (stdio ones are processes of the daemon).@@ -291,6 +318,33 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {};}+/** What the desktop app asks over its channel: a window's connector change, or its computer helper. */+async function appRequest(+ method: string,+ params: unknown,+ bridge: DotBridge,+ connectors: ConnectorManager,+ app: AppChannel,+): Promise<object> {+ const fields = (typeof params === "object" && params !== null ? params : {}) as Record<string, unknown>;+ switch (method) {+ case "command":+ await bridge.handleFromApp(String(fields.clientId ?? ""), fields.message);+ return {};+ case "computer_register": {+ const parsed = parseClientMessage(JSON.stringify({ ...fields, type: "computer_register" }));+ if (parsed?.type !== "computer_register") throw new Error("That is not the computer helper's address.");+ connectors.registerComputer(app, { url: parsed.url, token: parsed.token });+ return {};+ }+ case "computer_unregister":+ connectors.unregisterComputer(app);+ return {};+ default:+ throw new Error(`Unknown request: ${method}`);+ }+}+function mcpCliFromEnv(env: NodeJS.ProcessEnv): McpCli | undefined {if (!env.GENTLE_DOT_MCP_CLI) return undefined;const [command, ...args] = JSON.parse(env.GENTLE_DOT_MCP_CLI) as string[];diff --git a/packages/daemon/src/extensions/approval-guard.ts b/packages/daemon/src/extensions/approval-guard.tsindex 6eb1874..f9d97d8 100644--- a/packages/daemon/src/extensions/approval-guard.ts+++ b/packages/daemon/src/extensions/approval-guard.ts@@ -305,6 +305,32 @@ export function approvalCard(};}+/**+ * The same approval for the desktop app's native dialog (S25.3): the action in words and every+ * argument as its own field, key fields first. The app sanitizes and shortens what it shows.+ */+export function approvalRequest(+ name: string,+ server: string,+ tool: string,+ input: Record<string, unknown>,+): { connector: string; action: string; preview: { name: string; value: unknown }[] } {+ return {+ connector: name,+ action: describeAction(tool, server),+ preview: rankedKeys(input).map((key) => ({ name: key, value: input[key] })),+ };+}++/** The argument names, key fields first. */+function rankedKeys(input: Record<string, unknown>): string[] {+ const rank = (key: string) => {+ const index = KEY_FIELDS.findIndex((pattern) => pattern.test(key));+ return index < 0 ? KEY_FIELDS.length : index;+ };+ return Object.keys(input).sort((a, b) => rank(a) - rank(b));+}+/** `notion_create_pages` (or `notion-create-pages`) of `notion` -> "create pages". */function describeAction(tool: string, server: string): string {let action = tool;@@ -316,12 +342,7 @@ function describeAction(tool: string, server: string): string {/** Every argument, key fields first, so the user approves what they saw; very long ones say what was cut. */function preview(input: Record<string, unknown>): string {- const rank = (key: string) => {- const index = KEY_FIELDS.findIndex((pattern) => pattern.test(key));- return index < 0 ? KEY_FIELDS.length : index;- };- const text = Object.keys(input)- .sort((a, b) => rank(a) - rank(b))+ const text = rankedKeys(input).map((key) => `${key}: ${show(input[key])}`).join("\n");if (text.length <= PREVIEW_LIMIT) return text;diff --git a/packages/daemon/test/app-channel-fd.test.ts b/packages/daemon/test/app-channel-fd.test.tsnew file mode 100644index 0000000..fe61fa5--- /dev/null+++ b/packages/daemon/test/app-channel-fd.test.ts@@ -0,0 +1,84 @@+// The app's end of the channel reaches the daemon on fd 3 and goes no further (S25.1): children+// the daemon spawns (the engine, stdio servers, sign-in commands) never hold it, and a platform+// where they would gets no channel at all (fail closed).+import { spawn } from "node:child_process";+import { createServer, type Socket, connect as unixConnect } from "node:net";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterEach, describe, expect, it } from "vitest";+import { tempDir } from "./helpers.ts";++const CHILD = fileURLToPath(new URL("./fixtures/app-channel-child.ts", import.meta.url));++const cleanups: (() => void)[] = [];+afterEach(() => {+ for (const cleanup of cleanups.splice(0)) cleanup();+});++/** A connected pair of Unix sockets (Node has no socketpair): the app's end and the daemon's. */+async function socketPair(): Promise<{ app: Socket; daemon: Socket }> {+ const path = join(tempDir(), "pair.sock");+ const server = createServer();+ await new Promise<void>((done) => server.listen(path, done));+ const accepted = new Promise<Socket>((resolve) => server.once("connection", resolve));+ const daemon = unixConnect(path);+ await new Promise((resolve) => daemon.once("connect", resolve));+ const app = await accepted;+ server.close();+ cleanups.push(() => app.destroy());+ return { app, daemon };+}++/** Runs the stand-in with the daemon's end on fd 3, then drops the test's copy of it. */+async function runChild(mode: "normal" | "leak") {+ const { app, daemon } = await socketPair();+ const child = spawn(process.execPath, [CHILD, mode], { stdio: ["ignore", "pipe", "pipe", daemon] });+ daemon.destroy();+ let stdout = "";+ let stderr = "";+ child.stdout?.on("data", (chunk: Buffer) => {+ stdout += chunk.toString();+ });+ child.stderr?.on("data", (chunk: Buffer) => {+ stderr += chunk.toString();+ });+ const lines: Record<string, unknown>[] = [];+ let buffer = "";+ app.setEncoding("utf8");+ app.on("data", (chunk: string) => {+ buffer += chunk;+ for (let end = buffer.indexOf("\n"); end >= 0; end = buffer.indexOf("\n")) {+ const frame = JSON.parse(buffer.slice(0, end)) as Record<string, unknown>;+ buffer = buffer.slice(end + 1);+ lines.push(frame);+ if (frame.kind === "request")+ app.write(`${JSON.stringify({ kind: "response", id: frame.id, result: {} })}\n`);+ }+ });+ const code = await new Promise<number | null>((resolve) => child.on("close", resolve));+ return { code, stdout, stderr, lines };+}++describe("the app channel on fd 3 (S25.1)", () => {+ it("is opened by the daemon and never reaches the children it spawns", async () => {+ const { code, stderr, lines } = await runChild("normal");+ expect(code, stderr).toBe(0);+ const report = lines.find((frame) => frame.method === "report")?.params as Record<string, unknown>;+ expect(report, stderr).toBeDefined();+ expect(report.identity).toMatch(/^-?\d+:\d+$/);+ // A child that inherited it would print the same socket identity.+ expect(report.fromSpawn).not.toBe(report.identity);+ expect(report.fromSpawnSync).not.toBe(report.identity);+ expect(report.fromShell).toBe("none");+ // The probe the daemon runs at startup does see a leak when there is one.+ expect(report.detectsALeak).toBe(true);+ });++ it("is refused and closed where a child would inherit it", async () => {+ const { code, stdout, stderr, lines } = await runChild("leak");+ expect(code, stderr).toBe(0);+ expect(JSON.parse(stdout)).toEqual({ refused: true, closed: true });+ expect(lines).toEqual([]);+ expect(stderr).toMatch(/children would inherit/);+ });+});diff --git a/packages/daemon/test/app-channel.test.ts b/packages/daemon/test/app-channel.test.tsnew file mode 100644index 0000000..48dbc60--- /dev/null+++ b/packages/daemon/test/app-channel.test.ts@@ -0,0 +1,275 @@+// Privileged actions only through the desktop app's private channel (S25.1–S25.3): a window with the+// access key (the agent could be one, L49) cannot change connectors, approve a draft, import, or+// register the computer helper; the app can, and confirms natively what widens access.+import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { APP_REQUIRED, type ServerMessage } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import WebSocket from "ws";+import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { fakeApp } from "./fake-app.ts";+import { fakeAuthRuntime } from "./fake-auth-runtime.ts";+import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";++const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));+const HELPER = "http://127.0.0.1:51234/mcp";+const KEY = "s3cr3t-Computer-Key-0123456789abcdef";++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++/** Notion on, read only (no sign-in needed to change its mode), and Linear added but off. */+const SAVED = {+ version: 1,+ connectors: {+ notion: { enabled: true, mode: "read_only" },+ linear: { enabled: false, mode: "read_only" },+ },+};++const IMPORTABLE = {+ "Library/Application Support/Claude/claude_desktop_config.json": {+ mcpServers: { files: { command: "npx", args: ["-y", "@modelcontextprotocol/[email protected]"] } },+ },+};++const GITHUB_DRAFT = {+ name: "GitHub",+ description: "Issues and pull requests.",+ transport: "stdio",+ command: "npx",+ args: ["-y", "@modelcontextprotocol/[email protected]"],+ env_names: [],+};++async function setup(options: { channel?: boolean } = {}) {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ const importHome = join(dataDir, "import-home");+ writeFileSync(join(dataDir, "connectors.json"), JSON.stringify(SAVED));+ for (const [path, content] of Object.entries(IMPORTABLE)) {+ mkdirSync(dirname(join(importHome, path)), { recursive: true });+ writeFileSync(join(importHome, path), JSON.stringify(content));+ }+ const app = fakeApp();+ const fake = fakeAuthRuntime();+ const d = await startDaemon({+ port: 0,+ host: "127.0.0.1",+ dataDir,+ workspace: join(dataDir, "workspace"),+ uiDir: dataDir,+ agentCommand: process.execPath,+ agentArgs: [FAKE_AGENT],+ agentHome,+ backoffMs: [50],+ agentEnv: { ...process.env, FAKE_MCP_CLI_MODE: "auto" },+ authRuntime: async () => fake.runtime,+ connectorCli: { command: process.execPath, args: [FAKE_CLI] },+ importHome,+ ...(options.channel === false ? {} : { appChannel: app.daemonEnd }),+ });+ daemons.push(d);+ const mcpFile = join(agentHome, "mcp.json");+ const files = () => ({+ connectors: readFileSync(join(dataDir, "connectors.json"), "utf8"),+ mcp: existsSync(mcpFile) ? readFileSync(mcpFile, "utf8") : "",+ });+ const servers = (): Record<string, unknown> => JSON.parse(files().mcp || "{}").mcpServers ?? {};+ const saved = () =>+ JSON.parse(files().connectors).connectors as Record<string, { enabled: boolean; mode: string }>;+ return { d, app, files, servers, saved, ...(await connect(d)) };+}++async function connect(d: DotDaemon) {+ const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);+ const messages: ServerMessage[] = [];+ ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));+ await new Promise((resolve) => ws.on("open", resolve));+ ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));+ const ready = await waitFor(() => messages.find((m) => m.type === "ready"));+ const clientId = ready.type === "ready" ? ready.clientId : undefined;+ const send = (m: object) => ws.send(JSON.stringify(m));+ function find<T extends ServerMessage["type"]>(+ type: T,+ where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,+ ) {+ return waitFor(() =>+ messages.find(+ (m): m is Extract<ServerMessage, { type: T }> =>+ m.type === type && where(m as Extract<ServerMessage, { type: T }>),+ ),+ );+ }+ return { ws, messages, send, find, clientId: clientId ?? "" };+}++const settle = (ms = 200) => new Promise((resolve) => setTimeout(resolve, ms));++/** Every message a window cannot send any more, with what makes each one meaningful here. */+function privileged(draftId: string, importId: string): object[] {+ return [+ { type: "connector_mode", connectorId: "notion", mode: "read_write" },+ { type: "connector_mode", connectorId: "notion", mode: "read_only" },+ { type: "connector_connect", connectorId: "linear" },+ { type: "connector_signin", connectorId: "notion" },+ { type: "connector_setup", connectorId: "slack" },+ { type: "connector_disconnect", connectorId: "notion" },+ { type: "connector_remove", connectorId: "notion" },+ { type: "connector_import", ids: [importId] },+ { type: "connector_draft_reply", draftId, approve: true },+ { type: "computer_register", url: HELPER, token: KEY },+ { type: "computer_unregister" },+ ];+}++async function draftAndScan(window: Awaited<ReturnType<typeof connect>>) {+ window.send({ type: "send", text: `propose:${JSON.stringify(GITHUB_DRAFT)}` });+ const { draft } = await window.find("connector_draft");+ window.send({ type: "connectors_scan" });+ const { found } = await window.find("connector_imports");+ const importId = found[0]?.id ?? "";+ return { draftId: draft.draftId, importId };+}++describe("a window with the access key (S25.2)", () => {+ it("cannot change connectors, approve a draft, import, or register the computer: each is refused and nothing changes", async () => {+ const window = await setup();+ const { draftId, importId } = await draftAndScan(window);+ const before = window.files();+ const commands = privileged(draftId, importId);+ const seen = window.messages.length;+ for (const command of commands) window.send(command);+ const refusals = await waitFor(() => {+ const errors = window.messages.slice(seen).filter((m) => m.type === "error");+ return errors.length >= commands.length && errors;+ });+ expect(refusals).toEqual(+ commands.map(() => expect.objectContaining({ code: "app_required", message: APP_REQUIRED })),+ );+ await settle();+ expect(window.files()).toEqual(before);+ expect(window.servers().computer).toBeUndefined();+ expect(window.app.asked).toEqual([]);+ expect(window.messages.slice(seen).some((m) => m.type === "auth_prompt" || m.type === "auth_event")).toBe(+ false,+ );+ // The draft still waits for the app; declining it narrows nothing, so a window may.+ window.send({ type: "connector_draft_reply", draftId, approve: false });+ await window.find("connector_draft_resolved", (m) => m.draftId === draftId && !m.approved);+ expect(window.files()).toEqual(before);+ });++ it("gets an id for the app's commands on its behalf, which authorizes nothing by itself", async () => {+ const window = await setup();+ expect(window.clientId).toMatch(/^[A-Za-z0-9_-]{16,}$/);+ const other = await connect(window.d);+ expect(other.clientId).not.toBe(window.clientId);+ // The id only routes the app's command; a window that sends it is still refused.+ window.send({ type: "connector_disconnect", connectorId: "notion", clientId: window.clientId });+ await window.find("error", (m) => m.code === "app_required");+ await expect(+ window.app.command("not-a-window", { type: "connector_disconnect", connectorId: "notion" }),+ ).rejects.toThrow(/window/);+ await expect(window.app.command(window.clientId, { type: "send", text: "hi" })).rejects.toThrow(/app/);+ await settle();+ expect(window.saved().notion).toMatchObject({ enabled: true });+ });+});++describe("the desktop app's channel (S25.2, S25.3)", () => {+ it("changes a connector's mode; widening it is confirmed natively, narrowing it is not", async () => {+ const { app, clientId, saved, find, d } = await setup();+ app.answer("allow");+ const pid = d.supervisor.pid;+ await app.command(clientId, { type: "connector_mode", connectorId: "notion", mode: "read_write" });+ expect(saved().notion).toMatchObject({ mode: "read_write" });+ expect(app.asked).toEqual([+ expect.objectContaining({+ connector: "Notion",+ title: "Let Notion read and send?",+ summary: expect.stringContaining("asks you before each sending action"),+ }),+ ]);+ await find("connectors", (m) => m.connectors.find((c) => c.id === "notion")?.mode === "read_write");+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");++ await app.command(clientId, { type: "connector_mode", connectorId: "notion", mode: "read_only" });+ expect(saved().notion).toMatchObject({ mode: "read_only" });+ expect(app.asked).toHaveLength(1);+ });++ it("a widening change declined in the app changes nothing, and the window hears it", async () => {+ const { app, clientId, files, find } = await setup();+ const before = files();+ app.answer("decline");+ await app.command(clientId, { type: "connector_mode", connectorId: "notion", mode: "read_write" });+ await find("error", (m) => m.code === "declined");+ app.answer("decline");+ await app.command(clientId, { type: "connector_connect", connectorId: "linear" });+ expect(app.asked.map((a) => a.title)).toEqual(["Let Notion read and send?", "Connect Linear?"]);+ await settle();+ expect(files()).toEqual(before);+ });++ it("disconnects and removes without a dialog", async () => {+ const { app, clientId, saved } = await setup();+ await app.command(clientId, { type: "connector_disconnect", connectorId: "notion" });+ expect(saved().notion).toMatchObject({ enabled: false });+ await app.command(clientId, { type: "connector_remove", connectorId: "linear" });+ expect(saved().linear).toBeUndefined();+ expect(app.asked).toEqual([]);+ });++ it("approves a draft and imports a server after confirming each natively, with what will be added", async () => {+ const window = await setup();+ const { app, clientId, servers } = window;+ const { draftId, importId } = await draftAndScan(window);+ app.answer("allow", "allow");+ await app.command(clientId, { type: "connector_draft_reply", draftId, approve: true });+ await waitFor(() => servers().github);+ await window.find("connector_draft_resolved", (m) => m.draftId === draftId && m.approved);+ expect(app.asked[0]).toMatchObject({ title: "Add GitHub?", connector: "GitHub" });+ expect(JSON.stringify(app.asked[0]?.preview)).toContain("@modelcontextprotocol/[email protected]");++ await app.command(clientId, { type: "connector_import", ids: [importId] });+ const imported = await window.find("connector_imported");+ expect(imported.names).toHaveLength(1);+ expect(app.asked[1]).toMatchObject({ title: "Import 1 server?" });+ expect(JSON.stringify(app.asked[1]?.preview)).toContain("files");+ });++ it("registers the computer helper, which goes away when the app does (L61)", async () => {+ const { app, servers, d } = await setup();+ await app.request("computer_register", { url: HELPER, token: KEY });+ await waitFor(() => servers().computer);+ await expect(+ app.request("computer_register", { url: "http://evil.example/mcp", token: KEY }),+ ).rejects.toThrow();+ const pid = d.supervisor.pid;+ app.close();+ await waitFor(() => !servers().computer);+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");+ });+});++describe("without the app (S25.1: an attached daemon, pnpm dev, the web)", () => {+ it("fails closed with the reason", async () => {+ const window = await setup({ channel: false });+ const before = window.files();+ const { draftId, importId } = await draftAndScan(window);+ const commands = privileged(draftId, importId);+ const seen = window.messages.length;+ for (const command of commands) window.send(command);+ const refusals = await waitFor(() => {+ const errors = window.messages.slice(seen).filter((m) => m.type === "error");+ return errors.length >= commands.length && errors;+ });+ expect(refusals.every((m) => m.type === "error" && m.message === APP_REQUIRED)).toBe(true);+ await settle();+ expect(window.files()).toEqual(before);+ });+});diff --git a/packages/daemon/test/computer.test.ts b/packages/daemon/test/computer.test.tsindex bd721da..fce05e0 100644--- a/packages/daemon/test/computer.test.ts+++ b/packages/daemon/test/computer.test.ts@@ -5,6 +5,7 @@ import type { ConnectorInfo, ServerMessage } from "@gentle-dot/protocol";import { afterEach, describe, expect, it } from "vitest";import WebSocket from "ws";import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { fakeApp, sendLikeThePanel } from "./fake-app.ts";import { fakeAuthRuntime } from "./fake-auth-runtime.ts";import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";@@ -37,6 +38,8 @@ async function setup(options: Setup = {}) {writeFileSync(join(importHome, path), JSON.stringify(content));}const fake = fakeAuthRuntime();+ // The desktop app registers the helper and makes the connector changes (S25.2).+ const app = fakeApp([], "allow");const d = await startDaemon({port: 0,host: "127.0.0.1",@@ -55,6 +58,7 @@ async function setup(options: Setup = {}) {authRuntime: async () => fake.runtime,connectorCli: { command: process.execPath, args: [FAKE_CLI] },importHome,+ appChannel: app.daemonEnd,log: (line) => logs.push(line),});daemons.push(d);@@ -75,19 +79,25 @@ async function setup(options: Setup = {}) {servers,agentEnv,policy,- ...(await connect(d)),- connect: () => connect(d),+ app,+ ...(await connect(d, app)),+ connect: () => connect(d, app),};}-async function connect(d: DotDaemon) {+async function connect(d: DotDaemon, app: ReturnType<typeof fakeApp>) {const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);const messages: ServerMessage[] = [];ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));await new Promise((resolve) => ws.on("open", resolve));ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));- await waitFor(() => messages.some((m) => m.type === "ready"));- const send = (m: object) => ws.send(JSON.stringify(m));+ const ready = await waitFor(() => messages.find((m) => m.type === "ready"));+ const clientId = ready.type === "ready" ? (ready.clientId ?? "") : "";+ const send = sendLikeThePanel(+ app,+ () => clientId,+ (m) => ws.send(JSON.stringify(m)),+ );function find<T extends ServerMessage["type"]>(type: T,where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,@@ -199,16 +209,19 @@ describe("computer control registration (S24.7)", () => {}});- it("removes it on computer_unregister, which only the window that registered it can send", async () => {+ it("removes it on computer_unregister, which only the app can send (L61)", async () => {const { d, servers, send, list, connect: other } = await setup();const second = await other();send({ type: "computer_register", url: HELPER, token: KEY });await waitFor(() => servers().computer);const pid = d.supervisor.pid;- second.send({ type: "computer_unregister" });+ // A window with the access key (the agent could be one) cannot remove or repoint it.+ second.ws.send(JSON.stringify({ type: "computer_unregister" }));+ second.ws.send(JSON.stringify({ type: "computer_register", url: "http://127.0.0.1:9/mcp", token: KEY }));+ await second.find("error", (m) => m.code === "app_required");await settle();- expect(servers().computer).toBeDefined();+ expect(servers().computer).toMatchObject({ url: HELPER });send({ type: "computer_unregister" });await waitFor(() => !servers().computer);@@ -216,18 +229,17 @@ describe("computer control registration (S24.7)", () => {await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");});- it("removes it when the window that registered it disconnects, not when another one does", async () => {- const { servers, send, ws, connect: other } = await setup();+ it("stays while windows come and go, and goes away when the app does", async () => {+ const { servers, send, ws, app, connect: other } = await setup();const second = await other();- const third = await other();send({ type: "computer_register", url: HELPER, token: KEY });await waitFor(() => servers().computer);- third.ws.close();+ ws.close();await settle();expect(servers().computer).toBeDefined();- ws.close();+ app.close();await waitFor(() => !servers().computer);await second.find("connectors", (m) => computerOf(m.connectors) === undefined);expect(computerOf(await second.list())).toBeUndefined();diff --git a/packages/daemon/test/connector-drafts.test.ts b/packages/daemon/test/connector-drafts.test.tsindex e0bdb13..2bf8ea6 100644--- a/packages/daemon/test/connector-drafts.test.ts+++ b/packages/daemon/test/connector-drafts.test.ts@@ -15,6 +15,7 @@ import approvalGuard, {PROPOSE_TOOL,proposeConnector,} from "../src/extensions/approval-guard.ts";+import { fakeApp, sendLikeThePanel } from "./fake-app.ts";import { fakeAuthRuntime } from "./fake-auth-runtime.ts";import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";@@ -326,20 +327,30 @@ afterEach(async () => {await Promise.all(daemons.splice(0).map((d) => d.close()));});-async function connect(d: DotDaemon) {+async function connect(d: DotDaemon, app: ReturnType<typeof fakeApp>) {const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);const messages: ServerMessage[] = [];ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));await new Promise((resolve) => ws.on("open", resolve));ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));- await waitFor(() => messages.some((m) => m.type === "ready"));- return { ws, messages, send: (m: object) => ws.send(JSON.stringify(m)) };+ const ready = await waitFor(() => messages.find((m) => m.type === "ready"));+ const clientId = ready.type === "ready" ? (ready.clientId ?? "") : "";+ return {+ ws,+ messages,+ send: sendLikeThePanel(+ app,+ () => clientId,+ (m) => ws.send(JSON.stringify(m)),+ ),+ };}describe("connector drafts through the daemon", () => {it("shows the engine's draft as a card in every window; only the user's answer adds it", async () => {const dataDir = tempDir();const fake = fakeAuthRuntime();+ const app = fakeApp([], "allow");const d = await startDaemon({port: 0,host: "127.0.0.1",@@ -353,9 +364,10 @@ describe("connector drafts through the daemon", () => {authRuntime: async () => fake.runtime,connectorCli: { command: process.execPath, args: [FAKE_CLI] },importHome: tempDir(),+ appChannel: app.daemonEnd,});daemons.push(d);- const first = await connect(d);+ const first = await connect(d, app);first.send({ type: "send", text: `propose:${JSON.stringify({ ...stdioDraft, env_names: [] })}` });const card = await waitFor(() =>first.messages.find(@@ -364,7 +376,7 @@ describe("connector drafts through the daemon", () => {);expect(card.draft).toMatchObject({ name: "GitHub", command: "npx", envNames: [] });// A window that opens later sees the waiting card too.- const second = await connect(d);+ const second = await connect(d, app);await waitFor(() => second.messages.some((m) => m.type === "connector_draft"));const mcpFile = join(dataDir, "agent", "mcp.json");const before = existsSync(mcpFile) ? readFileSync(mcpFile, "utf8") : undefined;diff --git a/packages/daemon/test/connectors-gateway.test.ts b/packages/daemon/test/connectors-gateway.test.tsindex 50ed507..8ed79ef 100644--- a/packages/daemon/test/connectors-gateway.test.ts+++ b/packages/daemon/test/connectors-gateway.test.ts@@ -5,6 +5,7 @@ import type { ServerMessage } from "@gentle-dot/protocol";import { afterEach, describe, expect, it } from "vitest";import WebSocket from "ws";import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { fakeApp, sendLikeThePanel } from "./fake-app.ts";import { fakeAuthRuntime } from "./fake-auth-runtime.ts";import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";@@ -26,6 +27,8 @@ async function setup(options: { home?: boolean; cliMode?: "auto" } = {}) {const argsFile = join(dataDir, "agent-args.json");const logs: string[] = [];const fake = fakeAuthRuntime();+ // Connector changes come from the desktop app (S25.2); it allows the ones it confirms.+ const app = fakeApp([], "allow");const d = await startDaemon({port: 0,host: "127.0.0.1",@@ -44,6 +47,7 @@ async function setup(options: { home?: boolean; cliMode?: "auto" } = {}) {...(options.home ? { agentHome } : {}),authRuntime: async () => fake.runtime,connectorCli: { command: process.execPath, args: [FAKE_CLI] },+ appChannel: app.daemonEnd,log: (line) => logs.push(line),});daemons.push(d);@@ -56,19 +60,24 @@ async function setup(options: { home?: boolean; cliMode?: "auto" } = {}) {logs,agentEnv,agentArgs,- ...(await connect(d)),- connect: () => connect(d),+ ...(await connect(d, app)),+ connect: () => connect(d, app),};}-async function connect(d: DotDaemon) {+async function connect(d: DotDaemon, app: ReturnType<typeof fakeApp>) {const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);const messages: ServerMessage[] = [];ws.on("message", (data) => messages.push(JSON.parse(String(data)) as ServerMessage));await new Promise((resolve) => ws.on("open", resolve));ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));- await waitFor(() => messages.some((m) => m.type === "ready"));- const send = (m: object) => ws.send(JSON.stringify(m));+ const ready = await waitFor(() => messages.find((m) => m.type === "ready"));+ const clientId = ready.type === "ready" ? (ready.clientId ?? "") : "";+ const send = sendLikeThePanel(+ app,+ () => clientId,+ (m) => ws.send(JSON.stringify(m)),+ );function find<T extends ServerMessage["type"]>(type: T,where: (m: Extract<ServerMessage, { type: T }>) => boolean = () => true,diff --git a/packages/daemon/test/connectors-proxy-gateway.test.ts b/packages/daemon/test/connectors-proxy-gateway.test.tsindex 3aed691..f9dd4f4 100644--- a/packages/daemon/test/connectors-proxy-gateway.test.ts+++ b/packages/daemon/test/connectors-proxy-gateway.test.ts@@ -1,16 +1,18 @@// The MCP proxy inside the daemon, end to end with the fake agent (S25.4): the engine's mcp.json-// leads to the daemon, a read-only call runs without a card, a sending action asks once on the-// ask-card path, and a declined one never reaches the server.+// leads to the daemon, a read-only call runs without asking, and a sending action is asked once in+// the desktop app's native dialog (S25.3); windows only see that it waits there. Declined, not+// answered, or the app gone: it never reaches the server.import { readFileSync } from "node:fs";import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";import { join } from "node:path";import { fileURLToPath } from "node:url";-import { McpClient, McpError, StreamableHttpTransport, type Tool } from "@earendil-works/pi-mcp";-import type { ServerMessage } from "@gentle-dot/protocol";+import { McpClient, type McpError, StreamableHttpTransport, type Tool } from "@earendil-works/pi-mcp";+import { APP_REQUIRED, type ServerMessage } from "@gentle-dot/protocol";import { afterEach, describe, expect, it } from "vitest";import WebSocket from "ws";import { type DotDaemon, startDaemon } from "../src/daemon.ts";+import { fakeApp, sendLikeThePanel } from "./fake-app.ts";import { fakeAuthRuntime } from "./fake-auth-runtime.ts";import { FAKE_AGENT, tempDir, waitFor } from "./helpers.ts";@@ -77,6 +79,7 @@ async function setup() {const agentHome = join(dataDir, "agent");const notion = await fakeNotion();const fake = fakeAuthRuntime();+ const app = fakeApp([], "allow");const d = await startDaemon({port: 0,host: "127.0.0.1",@@ -98,6 +101,9 @@ async function setup() {...(credentials.authProvider ? { authProvider: credentials.authProvider } : {}),openGetStream: false,}),+ appChannel: app.daemonEnd,+ // The app declines on its own after 120 s; a short wait here stands in for that.+ approvalWaitMs: 1000,});daemons.push(d);const ws = new WebSocket(`ws://127.0.0.1:${d.port}/ws`);@@ -106,8 +112,14 @@ async function setup() {await new Promise((resolve) => ws.on("open", resolve));closers.push(async () => ws.close());ws.send(JSON.stringify({ type: "hello", token: d.token, protocol: 1 }));- await waitFor(() => messages.some((m) => m.type === "ready"));- const send = (m: object) => ws.send(JSON.stringify(m));+ const ready = await waitFor(() => messages.find((m) => m.type === "ready"));+ const clientId = ready.type === "ready" ? (ready.clientId ?? "") : "";+ const send = sendLikeThePanel(+ app,+ () => clientId,+ (m) => ws.send(JSON.stringify(m)),+ );+ const raw = (m: object) => ws.send(JSON.stringify(m));const mcpText = () => readFileSync(join(agentHome, "mcp.json"), "utf8");/** Connects to a server of the engine's mcp.json exactly as the engine would: its URL and headers. */const engineClient = async (id: string) => {@@ -122,12 +134,12 @@ async function setup() {ws.once("close", () => done());ws.close();});- return { d, dataDir, agentHome, notion, messages, send, mcpText, engineClient, closeWindow };+ return { d, dataDir, agentHome, notion, app, messages, send, raw, mcpText, engineClient, closeWindow };}describe("connectors through the daemon's proxy (regression, S25.4)", () => {- it("connects, then a read-only call reaches the server with the stored sign-in and no card", async () => {- const { d, notion, send, messages, mcpText, engineClient } = await setup();+ it("connects, then a read-only call reaches the server with the stored sign-in without asking", async () => {+ const { d, notion, app, send, messages, mcpText, engineClient } = await setup();const pid = d.supervisor.pid;send({ type: "connector_connect", connectorId: "notion" });await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));@@ -145,11 +157,13 @@ describe("connectors through the daemon's proxy (regression, S25.4)", () => {});expect(notion.calls()).toEqual(["notion-search"]);for (const request of notion.seen) expect(request.authorization).toBe(`Bearer ${SIGNED_IN_TOKEN}`);- expect(messages.some((m) => m.type === "ask")).toBe(false);+ // Only connecting it was confirmed.+ expect(app.asked.map((a) => a.title)).toEqual(["Connect Notion?"]);+ expect(messages.filter((m) => m.type === "ask")).toHaveLength(1);});- it("asks once before a sending action in read and send, forwards nothing when declined, and runs it when allowed", async () => {- const { d, notion, send, messages, mcpText, engineClient } = await setup();+ it("asks the app once before a sending action: declined or unanswered sends nothing, allowed runs it, and windows cannot answer", async () => {+ const { d, notion, app, send, raw, messages, mcpText, engineClient } = await setup();send({ type: "connector_connect", connectorId: "notion" });await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));const pid = d.supervisor.pid;@@ -158,34 +172,54 @@ describe("connectors through the daemon's proxy (regression, S25.4)", () => {const oldKey = JSON.parse(mcpText()).mcpServers.notion.headers.Authorization;const client = await engineClient("notion");expect((await client.listTools()).map((t) => t.name)).toEqual(["notion-search", "notion-create-pages"]);- const args = { parent: "Team space", title: "Plan", content: "x".repeat(9000) };+ const args = { content: "x".repeat(9000), title: "Plan", parent: "Team space" };+ const refusal = (call: Promise<unknown>) =>+ call.then(+ () => undefined,+ (e: unknown) => e as McpError,+ );+ const asked = app.asked.length;- const declined = client.callTool("notion-create-pages", args);- const ask = await waitFor(() => messages.find((m) => m.type === "ask"));+ // No answer: windows see that it waits in the app, and answering there does nothing.+ app.answer("hang");+ const unanswered = refusal(client.callTool("notion-create-pages", args));+ const ask = await waitFor(() =>+ messages.find((m) => m.type === "ask" && m.ask.title === "Allow Notion to create pages?"),+ );if (ask.type !== "ask") throw new Error("not an ask");- expect(ask.ask).toMatchObject({ method: "confirm", title: "Allow Notion to create pages?" });- expect(ask.ask.message).toContain("parent: Team space");- expect(ask.ask.message).toContain("title: Plan");+ expect(ask.ask).toEqual({+ requestId: expect.any(String),+ method: "app",+ title: "Allow Notion to create pages?",+ message: "Waiting for your answer in the Gentle Dot app.",+ });await waitFor(() => d.bridge.agentState === "needs_you");- send({ type: "ui_response", requestId: ask.ask.requestId, confirmed: false });- const error = await declined.then(- () => undefined,- (e: unknown) => e,- );- expect(error).toBeInstanceOf(McpError);- expect((error as McpError).message).toMatch(/did not allow/);+ raw({ type: "ui_response", requestId: ask.ask.requestId, confirmed: true });+ await waitFor(() => messages.find((m) => m.type === "error" && m.code === "app_required"));+ expect((await unanswered)?.message).toMatch(/did not allow/);expect(notion.calls()).toEqual([]);await waitFor(() => messages.find((m) => m.type === "ask_resolved" && m.requestId === ask.ask.requestId));+ // The app showed the full preview, key fields first (in the order the agent gave them).+ expect(app.asked[asked]).toEqual({+ connector: "Notion",+ action: "create pages",+ preview: [+ { name: "title", value: "Plan" },+ { name: "parent", value: "Team space" },+ { name: "content", value: args.content },+ ],+ });- const allowed = client.callTool("notion-create-pages", args);- const second = await waitFor(() =>- messages.find((m) => m.type === "ask" && m.ask.requestId !== ask.ask.requestId),- );- if (second.type !== "ask") throw new Error("not an ask");- send({ type: "ui_response", requestId: second.ask.requestId, confirmed: true });- expect(await allowed).toMatchObject({ content: [{ text: "notion ran notion-create-pages" }] });+ app.answer("decline");+ expect((await refusal(client.callTool("notion-create-pages", args)))?.message).toMatch(/did not allow/);+ expect(notion.calls()).toEqual([]);++ app.answer("allow");+ expect(await client.callTool("notion-create-pages", args)).toMatchObject({+ content: [{ text: "notion ran notion-create-pages" }],+ });expect(notion.calls()).toEqual(["notion-create-pages"]);- expect(messages.filter((m) => m.type === "ask")).toHaveLength(2);+ expect(app.asked).toHaveLength(asked + 3);// The next engine launch gets a new key; the old one no longer works.const restarted = d.supervisor.pid;@@ -201,21 +235,34 @@ describe("connectors through the daemon's proxy (regression, S25.4)", () => {expect(stale.status).toBe(401);});- it("refuses a sending action when no window can answer", async () => {- const { d, notion, send, messages, engineClient, closeWindow } = await setup();+ it("refuses a sending action when the app quits while asking, and when there is no app", async () => {+ const { d, notion, app, send, raw, messages, engineClient } = await setup();send({ type: "connector_connect", connectorId: "notion" });await waitFor(() => messages.find((m) => m.type === "auth_done" && m.ok));const pid = d.supervisor.pid;send({ type: "connector_mode", connectorId: "notion", mode: "read_write" });await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");const client = await engineClient("notion");- await closeWindow();- await new Promise((resolve) => setTimeout(resolve, 100));- const error = await client.callTool("notion-create-pages", { title: "x" }).then(- () => undefined,- (e: unknown) => e,+ const failure = (call: Promise<unknown>) =>+ call.then(+ () => undefined,+ (e: unknown) => e as McpError,+ );++ app.answer("hang");+ const pending = failure(client.callTool("notion-create-pages", { title: "x" }));+ await waitFor(() =>+ messages.find((m) => m.type === "ask" && m.ask.title === "Allow Notion to create pages?"),+ );+ app.close();+ expect((await pending)?.message).toMatch(/did not allow/);++ expect((await failure(client.callTool("notion-create-pages", { title: "y" })))?.message).toMatch(+ /approval/,);- expect((error as McpError).message).toMatch(/approval/);expect(notion.calls()).toEqual([]);+ // And a window cannot turn it back on or change it without the app.+ raw({ type: "connector_mode", connectorId: "notion", mode: "read_only" });+ await waitFor(() => messages.find((m) => m.type === "error" && m.message === APP_REQUIRED));});});diff --git a/packages/daemon/test/connectors-proxy.test.ts b/packages/daemon/test/connectors-proxy.test.tsindex a6f2663..269d9f4 100644--- a/packages/daemon/test/connectors-proxy.test.ts+++ b/packages/daemon/test/connectors-proxy.test.ts@@ -262,13 +262,59 @@ describe("the daemon's sign-in home", () => {expect(statSync(s.authFile).mode & 0o777).toBe(0o600);expect(s.isSignedIn("notion")).toBe(true);expect(s.isSignedIn("linear")).toBe(false);- // Not again: a file that shows up in the engine's home later is not taken over.+ // A file that shows up in the engine's home later never replaces a sign-in the daemon holds,+ // and it does not stay there.writeFileSync(old, JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "planted" } } }));const next = make();expect(readFileSync(next.authFile, "utf8")).toBe(stored);+ expect(existsSync(old)).toBe(false);expect(readdirSync(join(dataDir, "connector-signin")).filter((f) => f.includes(".tmp"))).toEqual([]);});+ it("finishes a move that stopped halfway: an empty sign-in home, the old file still there (A2)", () => {+ const { make, agentHome, dataDir } = setup();+ const old = join(agentHome, "mcp-auth.json");+ const stored = JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: SECRETS.oauthAccess } } });+ writeFileSync(old, stored);+ mkdirSync(join(dataDir, "connector-signin"), { mode: 0o700 });+ const s = make();+ expect(existsSync(old)).toBe(false);+ expect(readFileSync(s.authFile, "utf8")).toBe(stored);+ expect(s.isSignedIn("notion")).toBe(true);+ });++ it("moves the sign-ins the daemon does not hold yet when both files exist, keeping its own (A2)", () => {+ const { make, agentHome, dataDir } = setup();+ const old = join(agentHome, "mcp-auth.json");+ const linearKey = NOTION_KEY.replace("notion", "linear").replace("mcp.notion.com", "mcp.linear.app");+ writeFileSync(+ old,+ JSON.stringify({+ [NOTION_KEY]: { tokens: { access_token: "older-notion" } },+ [linearKey]: { tokens: { access_token: SECRETS.oauthAccess } },+ }),+ );+ mkdirSync(join(dataDir, "connector-signin"), { mode: 0o700 });+ const current = { [NOTION_KEY]: { tokens: { access_token: "current-notion" } } };+ writeFileSync(join(dataDir, "connector-signin", "mcp-auth.json"), JSON.stringify(current));+ const s = make();+ expect(existsSync(old)).toBe(false);+ const moved = JSON.parse(readFileSync(s.authFile, "utf8"));+ expect(moved[NOTION_KEY].tokens.access_token).toBe("current-notion");+ expect(moved[linearKey].tokens.access_token).toBe(SECRETS.oauthAccess);+ expect(statSync(s.authFile).mode & 0o777).toBe(0o600);+ });++ it("leaves the old file where it is when it cannot be read as sign-ins (A2)", () => {+ const { make, agentHome, dataDir } = setup();+ const old = join(agentHome, "mcp-auth.json");+ mkdirSync(join(dataDir, "connector-signin"), { mode: 0o700 });+ writeFileSync(join(dataDir, "connector-signin", "mcp-auth.json"), "{}");+ writeFileSync(old, "not json");+ make();+ expect(readFileSync(old, "utf8")).toBe("not json");+ });+it("protects the sign-in home and its files from the file tools and shell commands like the other credential files", () => {const { make, agentHome, dataDir } = setup();const s = make();diff --git a/packages/daemon/test/fake-app.ts b/packages/daemon/test/fake-app.tsnew file mode 100644index 0000000..f11698f--- /dev/null+++ b/packages/daemon/test/fake-app.ts@@ -0,0 +1,98 @@+import { type Duplex, duplexPair } from "node:stream";+import { isAppCommand, parseClientMessage } from "@gentle-dot/protocol";++/** One approval the daemon asked the app for (the native dialog's content). */+export interface AskedApproval {+ connector: string;+ action: string;+ title?: string;+ summary?: string;+ preview: { name: string; value: unknown }[];+}++/** What the fake app answers: allow, decline, or never answer. */+export type Answer = "allow" | "decline" | "hang";++type Frame =+ | { kind: "request"; id: number; method: string; params?: unknown }+ | { kind: "response"; id: number; result?: unknown; error?: string };++/**+ * The desktop app's end of its private channel, for tests: the daemon gets `daemonEnd` (in+ * production the socket on fd 3), and the test drives the app's side with line-delimited JSON.+ */+export function fakeApp(answers: Answer[] = [], otherwise: Answer = "decline") {+ const [daemonEnd, appEnd] = duplexPair();+ const asked: AskedApproval[] = [];+ const queue = [...answers];+ const pending = new Map<number, { resolve(v: unknown): void; reject(e: Error): void }>();+ let nextId = 0;+ let buffer = "";+ const write = (frame: Frame) => appEnd.write(`${JSON.stringify(frame)}\n`);+ appEnd.setEncoding("utf8");+ appEnd.on("data", (chunk: string) => {+ buffer += chunk;+ for (let end = buffer.indexOf("\n"); end >= 0; end = buffer.indexOf("\n")) {+ const frame = JSON.parse(buffer.slice(0, end)) as Frame;+ buffer = buffer.slice(end + 1);+ if (frame.kind === "response") {+ const waiting = pending.get(frame.id);+ pending.delete(frame.id);+ if (frame.error !== undefined) waiting?.reject(new Error(frame.error));+ else waiting?.resolve(frame.result);+ continue;+ }+ if (frame.method !== "approve") {+ write({ kind: "response", id: frame.id, error: `unknown method ${frame.method}` });+ continue;+ }+ asked.push(frame.params as AskedApproval);+ const answer = queue.shift() ?? otherwise;+ if (answer !== "hang")+ write({ kind: "response", id: frame.id, result: { approved: answer === "allow" } });+ }+ });+ const request = (method: string, params: unknown = {}) =>+ new Promise<unknown>((resolve, reject) => {+ const id = ++nextId;+ pending.set(id, { resolve, reject });+ write({ kind: "request", id, method, params });+ });+ return {+ daemonEnd: daemonEnd as Duplex,+ asked,+ /** Queues the answers to the next approvals. */+ answer: (...next: Answer[]) => queue.push(...next),+ request,+ /** A privileged command on behalf of the window with `clientId` (its sign-in steps go there). */+ command: (clientId: string, message: object) => request("command", { clientId, message }),+ /** The app quits: its end of the channel closes (the daemon reads end of file). */+ close: () => appEnd.end(),+ };+}++/**+ * A window's `send` as the desktop panel does it: app commands go through the app's channel on+ * behalf of the window (`clientId`), the computer helper is registered by the app itself, and+ * everything else goes over the WebSocket.+ */+export function sendLikeThePanel(+ app: ReturnType<typeof fakeApp>,+ clientId: () => string,+ overWebSocket: (message: object) => void,+): (message: object) => void {+ return (message) => {+ const parsed = parseClientMessage(JSON.stringify(message));+ if (!parsed || !isAppCommand(parsed)) {+ overWebSocket(message);+ return;+ }+ const sent =+ parsed.type === "computer_register"+ ? app.request("computer_register", { url: parsed.url, token: parsed.token })+ : parsed.type === "computer_unregister"+ ? app.request("computer_unregister")+ : app.command(clientId(), message);+ void sent.catch(() => {});+ };+}diff --git a/packages/daemon/test/fixtures/app-channel-child.ts b/packages/daemon/test/fixtures/app-channel-child.tsnew file mode 100644index 0000000..eed7e10--- /dev/null+++ b/packages/daemon/test/fixtures/app-channel-child.ts@@ -0,0 +1,60 @@+#!/usr/bin/env node+// A daemon stand-in that received the desktop app's end of the channel on fd 3 (like the real+// daemon, spawned by the app). It opens the channel the way cli.ts does, spawns children the way+// the daemon spawns the engine and stdio servers, and reports over the channel what each child saw+// on fd 3. Argument "leak": open with a probe that passes fd 3 on, as a platform that leaks would.+import { execFileSync, spawn, spawnSync } from "node:child_process";+import { fstatSync } from "node:fs";+import { childInherits, openInheritedChannel } from "../../src/app-channel.ts";++/** What a child sees on fd 3: the socket's identity, or "none". */+const PRINT_FD3 =+ "try{const s=require('fs').fstatSync(3,{bigint:true});console.log(s.isSocket()?s.dev+':'+s.ino:'other')}catch{console.log('none')}";++const own = fstatSync(3, { bigint: true });+const identity = `${own.dev}:${own.ino}`;+const leak = process.argv[2] === "leak";+const channel = openInheritedChannel({+ log: (line) => process.stderr.write(`${line}\n`),+ ...(leak+ ? { probe: (fd: number, id: string) => childInherits(fd, id, ["ignore", "pipe", "ignore", fd]) }+ : {}),+});+if (!channel) {+ // Refused: fd 3 must be closed too, so nothing below could pass it on.+ let closed = false;+ try {+ fstatSync(3);+ } catch {+ closed = true;+ }+ process.stdout.write(`${JSON.stringify({ refused: true, closed })}\n`);+ process.exit(0);+}++const fromSpawn = await new Promise<string>((resolve) => {+ // Like the supervisor starts the engine: pipes for stdio and nothing else.+ const child = spawn(process.execPath, ["-e", PRINT_FD3], { stdio: ["pipe", "pipe", "pipe"] });+ let out = "";+ child.stdout.on("data", (chunk: Buffer) => {+ out += chunk.toString();+ });+ child.on("close", () => resolve(out.trim()));+});+const fromSpawnSync = spawnSync(process.execPath, ["-e", PRINT_FD3], { encoding: "utf8" }).stdout.trim();+const fromShell = execFileSync("/bin/sh", ["-c", "if [ -e /dev/fd/3 ]; then echo open; else echo none; fi"], {+ encoding: "utf8",+}).trim();+channel.handler = async (method, params) => (method === "echo" ? params : undefined);+await channel.request(+ "report",+ {+ identity,+ fromSpawn,+ fromSpawnSync,+ fromShell,+ detectsALeak: childInherits(3, identity, ["ignore", "pipe", "ignore", 3]),+ },+ 5000,+);+channel.close();diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex aceffd1..c0cec56 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -20,7 +20,11 @@ export interface Activity {export interface Ask {requestId: string;- method: "select" | "confirm" | "input" | "editor";+ /**+ * `app`: an approval the desktop app asks in a native dialog (S25.3). Windows only show that it+ * waits there; it cannot be answered with `ui_response`.+ */+ method: "select" | "confirm" | "input" | "editor" | "app";title: string;message?: string;options?: string[];@@ -377,6 +381,11 @@ export type ServerPayload =| {type: "ready";agentState: AgentState;+ /**+ * This window's id for the desktop app's private channel: an app command on its behalf+ * (S25.2) sends its sign-in steps here. It authorizes nothing by itself.+ */+ clientId?: string;conversationId?: string;model?: string;features?: Features;@@ -448,6 +457,32 @@ export type ServerPayload =/** A voice request did not work; `reason` is plain words for the user. */| { type: "voice_unavailable"; requestId: string; reason: string };+/** Why a window cannot change connectors itself (S25.2). */+export const APP_REQUIRED = "Open the Gentle Dot app to change connectors.";++/**+ * Messages only the desktop app that launched the daemon may send, over its private channel+ * (S25.2): connector changes, approving a draft, importing, and the computer helper. Declining a+ * draft narrows nothing, so any window may.+ */+export const APP_COMMANDS = [+ "connector_connect",+ "connector_signin",+ "connector_setup",+ "connector_disconnect",+ "connector_remove",+ "connector_mode",+ "connector_draft_reply",+ "connector_import",+ "computer_register",+ "computer_unregister",+] as const satisfies readonly ClientMessage["type"][];++export function isAppCommand(message: ClientMessage): boolean {+ if (message.type === "connector_draft_reply") return message.approve;+ return (APP_COMMANDS as readonly string[]).includes(message.type);+}+/** Every daemon message carries a per-connection, monotonic `seq`. */export type ServerMessage = ServerPayload & { seq: number };diff --git a/packages/protocol/test/protocol.test.ts b/packages/protocol/test/protocol.test.tsindex 65ac9bf..234f8ef 100644--- a/packages/protocol/test/protocol.test.ts+++ b/packages/protocol/test/protocol.test.ts@@ -1,5 +1,7 @@import { describe, expect, it } from "vitest";import {+ APP_REQUIRED,+ isAppCommand,isValidProfileName,PROTOCOL_VERSION,parseClientMessage,@@ -318,3 +320,46 @@ describe("computer control messages", () => {}});});++describe("app-only commands (S25.2)", () => {+ const parse = (value: object) => parseClientMessage(JSON.stringify(value));++ it("are the connector changes, approving a draft, importing, and the computer helper", () => {+ for (const message of [+ { type: "connector_connect", connectorId: "notion" },+ { type: "connector_signin", connectorId: "notion" },+ { type: "connector_setup", connectorId: "notion" },+ { type: "connector_disconnect", connectorId: "notion" },+ { type: "connector_remove", connectorId: "notion" },+ { type: "connector_mode", connectorId: "notion", mode: "read_only" },+ { type: "connector_mode", connectorId: "notion", mode: "read_write" },+ { type: "connector_draft_reply", draftId: "d1", approve: true },+ { type: "connector_import", ids: ["claude:x"] },+ { type: "computer_register", url: "http://127.0.0.1:51234/mcp", token: "k3Y_0123456789abcdef" },+ { type: "computer_unregister" },+ ]) {+ const parsed = parse(message);+ expect(parsed, message.type).toBeDefined();+ expect(parsed && isAppCommand(parsed), message.type).toBe(true);+ }+ });++ it("leave the chat, the read-only lists, declining a draft, and everything else to every window", () => {+ for (const message of [+ { type: "send", text: "hi" },+ { type: "ui_response", requestId: "a", confirmed: true },+ { type: "connectors_list" },+ { type: "connectors_scan" },+ { type: "connector_draft_reply", draftId: "d1", approve: false },+ { type: "auth_login", providerId: "openai", method: "api_key" },+ { type: "auth_reply", flowId: "connector-x", value: "v" },+ { type: "profile_apply", name: "work" },+ { type: "models_list" },+ ]) {+ const parsed = parse(message);+ expect(parsed, message.type).toBeDefined();+ expect(parsed && isAppCommand(parsed), message.type).toBe(false);+ }+ expect(APP_REQUIRED).toBe("Open the Gentle Dot app to change connectors.");+ });+});diff --git a/packages/ui/src/App.tsx b/packages/ui/src/App.tsxindex 60d35f4..a90d70b 100644--- a/packages/ui/src/App.tsx+++ b/packages/ui/src/App.tsx@@ -1,4 +1,5 @@-import { useEffect, useMemo, useRef, useState } from "react";+import type { ClientMessage } from "@gentle-dot/protocol";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { type ConnectionInfo, tokenFromLocation } from "./client.ts";import { ChatSurface } from "./components/ChatSurface.tsx";import type { ComputerControls } from "./components/Computer.tsx";@@ -7,6 +8,7 @@ import { GlowSurface } from "./components/GlowSurface.tsx";import { computerPermissions, requestComputerPermission, setComputerYolo, stopComputer } from "./computer.ts";import {connectionInfo,+ connectorCommand,hidePanel,inDesktop,onDesktopEvent,@@ -15,7 +17,7 @@ import {togglePanel,} from "./desktop.ts";import { createUploader } from "./uploads.ts";-import { useComputerRegistration, useComputerState } from "./useComputer.ts";+import { useComputerAvailable, useComputerState } from "./useComputer.ts";import { useDot } from "./useDot.ts";import { usePanelWindow } from "./usePanelWindow.ts";@@ -70,10 +72,17 @@ function Assistant({ surface }: { surface: Surface }) {// Computer control lives in the desktop app only (S24.7); the panel registers the helper.const desktop = inDesktop();const { session: computerSession, yolo } = useComputerState(desktop && surface !== "web");- const computerAvailable = useComputerRegistration(- desktop && surface === "panel",- state.connection === "open",- send,+ const computerAvailable = useComputerAvailable(desktop && surface === "panel", state.connection === "open");+ // Connector changes go through the app, on behalf of this window (S25.2); the web page has none.+ const clientId = state.clientId;+ const appSend = useCallback(+ (message: ClientMessage) => {+ if (!clientId) return;+ connectorCommand(clientId, message).catch((error: unknown) =>+ dispatch({ type: "notice", level: "error", message: String(error) }),+ );+ },+ [clientId, dispatch],);// The panel's own window (S26): hide the rose, full screen.const panel = usePanelWindow(desktop && surface === "panel");@@ -171,6 +180,7 @@ function Assistant({ surface }: { surface: Surface }) {dispatch={dispatch}focusKey={focusKey}{...(surface === "panel" ? { onHide: hidePanel } : {})}+ {...(desktop && surface === "panel" ? { appSend } : {})}{...(computer ? { computer } : {})}{...(desktop && surface === "panel" ? { voiceModel: true } : {})}{...(desktop && surface === "panel" ? { panelWindow: panel.controls } : {})}diff --git a/packages/ui/src/components/AskCard.tsx b/packages/ui/src/components/AskCard.tsxindex ea4f150..57e42ea 100644--- a/packages/ui/src/components/AskCard.tsx+++ b/packages/ui/src/components/AskCard.tsx@@ -12,6 +12,17 @@ export function AskCard({ ask, send }: { ask: Ask; send: Send }) {const answer = (fields: { value?: string; confirmed?: boolean; cancelled?: boolean }) =>send({ type: "ui_response", requestId: ask.requestId, ...fields });+ // The desktop app asks this one in a native dialog (S25.3); here it only shows that it waits.+ if (ask.method === "app") {+ return (+ <section ref={card} className="ask-card" aria-label="Waiting for your answer in the app">+ <p className="eyebrow">Needs your answer</p>+ <p className="ask-title">{ask.title}</p>+ {ask.message ? <p className="connector-note">{ask.message}</p> : null}+ </section>+ );+ }+return (<section ref={card} className="ask-card" aria-label="The assistant needs your answer"><p className="eyebrow">Needs your answer</p>diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxindex 72aefb6..a21e727 100644--- a/packages/ui/src/components/ChatSurface.tsx+++ b/packages/ui/src/components/ChatSurface.tsx@@ -38,6 +38,11 @@ interface ChatSurfaceProps {variant: "web" | "panel";state: DotState;send: Send;+ /**+ * Connector changes (S25.2), through the desktop app on behalf of this window. Only the desktop+ * panel has it; elsewhere connector controls are disabled with the reason.+ */+ appSend?: Send;dismiss: (id: number) => void;onHide?: () => void;focusKey?: number;@@ -74,6 +79,7 @@ export function ChatSurface({variant,state,send,+ appSend,dismiss,onHide,focusKey,@@ -296,6 +302,7 @@ export function ChatSurface({<ConnectorsPanelconnectors={state.connectors}send={send}+ {...(appSend ? { appSend } : {})}dispatch={dispatch}openUrl={openUrl}{...(computer?.available ? { computer } : {})}@@ -350,6 +357,7 @@ export function ChatSurface({key={draft.draftId}draft={draft}send={send}+ {...(appSend ? { appSend } : {})}// Its secrets are asked in the Connectors screen.approved={() => dispatch({ type: "connector_started", connectorId: draft.name })}/>diff --git a/packages/ui/src/components/ConnectorDraftCard.tsx b/packages/ui/src/components/ConnectorDraftCard.tsxindex 8abc9c6..4a38113 100644--- a/packages/ui/src/components/ConnectorDraftCard.tsx+++ b/packages/ui/src/components/ConnectorDraftCard.tsx@@ -1,26 +1,28 @@-import type { ConnectorDraft } from "@gentle-dot/protocol";+import { APP_REQUIRED, type ConnectorDraft } from "@gentle-dot/protocol";import { useEffect, useRef } from "react";import type { Send } from "./types.ts";/*** A connector the assistant drafted. Every detail is shown; only "Add" adds it, read only with all- * of its tools hidden, and its secrets are then asked in the Connectors screen.+ * of its tools hidden, and its secrets are then asked in the Connectors screen. Adding goes through+ * the desktop app (`appSend`, S25.2), which confirms it natively; any window may decline.*/export function ConnectorDraftCard({draft,send,+ appSend,approved,}: {draft: ConnectorDraft;send: Send;+ appSend?: Send;approved: () => void;}) {const card = useRef<HTMLElement>(null);useEffect(() => {card.current?.scrollIntoView?.({ block: "nearest" });}, []);- const answer = (approve: boolean) =>- send({ type: "connector_draft_reply", draftId: draft.draftId, approve });+ const decline = () => send({ type: "connector_draft_reply", draftId: draft.draftId, approve: false });const runs = draft.transport === "http" ? draft.url : [draft.command, ...(draft.args ?? [])].join(" ");return (@@ -53,18 +55,20 @@ export function ConnectorDraftCard({<p className="connector-note">You type each secret in the app, never in the chat. It starts read only, with all of its tools hidden.</p>+ {appSend ? null : <p className="connector-note">{APP_REQUIRED}</p>}<div className="ask-options"><buttontype="button"className="primary"+ disabled={!appSend}onClick={() => {- answer(true);+ appSend?.({ type: "connector_draft_reply", draftId: draft.draftId, approve: true });approved();}}>Add {draft.name}</button>- <button type="button" onClick={() => answer(false)}>+ <button type="button" onClick={decline}>Decline</button></div>diff --git a/packages/ui/src/components/ConnectorsPanel.tsx b/packages/ui/src/components/ConnectorsPanel.tsxindex 1581ce1..85c0aa5 100644--- a/packages/ui/src/components/ConnectorsPanel.tsx+++ b/packages/ui/src/components/ConnectorsPanel.tsx@@ -1,4 +1,9 @@-import type { ConnectorInfo, ConnectorStatus, ImportCandidate } from "@gentle-dot/protocol";+import {+ APP_REQUIRED,+ type ConnectorInfo,+ type ConnectorStatus,+ type ImportCandidate,+} from "@gentle-dot/protocol";import { useState } from "react";import type { ConnectorsState, DotAction } from "../store.ts";import "../accounts.css";@@ -10,6 +15,11 @@ import { VoiceModelEntry } from "./VoiceModel.tsx";interface ConnectorsPanelProps {connectors: ConnectorsState;send: Send;+ /**+ * Connector changes, through the desktop app (S25.2). Without it (the web page, a VPS) the+ * controls are disabled with the reason; lists and sign-in answers still go over `send`.+ */+ appSend?: Send;dispatch: (action: DotAction) => void;openUrl: (url: string) => void;/** Computer control, in the desktop app on macOS only. */@@ -34,6 +44,7 @@ export const addConnectorRequest = (what: string) =>export function ConnectorsPanel({connectors,send,+ appSend,dispatch,openUrl,computer,@@ -48,9 +59,10 @@ export function ConnectorsPanel({connector: ConnectorInfo,type: "connector_connect" | "connector_signin" | "connector_setup",) => {+ if (!appSend) return;setGuideFor(undefined);dispatch({ type: "connector_started", connectorId: connector.id });- send({ type, connectorId: connector.id });+ appSend({ type, connectorId: connector.id });};const guided = connectors.list?.find((c) => c.id === guideFor && c.guide);// Values are asked first; once the sign-in page is on its way, it is a sign-in.@@ -72,6 +84,7 @@ export function ConnectorsPanel({<p className="muted">Let the assistant use your other apps. It always asks you before it sends or changes anything.</p>+ {appSend ? null : <p className="connector-note">{APP_REQUIRED}</p>}{flow ? (<div className="auth-flow">@@ -113,6 +126,7 @@ export function ConnectorsPanel({openUrl={openUrl}back={() => setGuideFor(undefined)}next={() => start(guided, "connector_connect")}+ canChange={appSend !== undefined}/>) : (<>@@ -137,7 +151,9 @@ export function ConnectorsPanel({{connectors.imports ? (<ImportListfound={connectors.imports}- importServers={(ids) => send({ type: "connector_import", ids })}+ {...(appSend+ ? { importServers: (ids: string[]) => appSend({ type: "connector_import", ids }) }+ : {})}close={() => dispatch({ type: "connector_imports_closed" })}/>) : null}@@ -156,7 +172,7 @@ export function ConnectorsPanel({<ConnectorRowkey={connector.id}connector={connector}- send={send}+ {...(appSend ? { appSend } : {})}connect={() =>connector.guide && !connector.added? setGuideFor(connector.id)@@ -180,10 +196,12 @@ interface ConnectorGuideViewProps {openUrl: (url: string) => void;back: () => void;next: () => void;+ /** False outside the desktop app: the guide reads, but Continue cannot connect. */+ canChange: boolean;}/** The steps to create the app or bot the connector signs in with, before "Connect". */-function ConnectorGuideView({ connector: c, openUrl, back, next }: ConnectorGuideViewProps) {+function ConnectorGuideView({ connector: c, openUrl, back, next, canChange }: ConnectorGuideViewProps) {const guide = c.guide;if (!guide) return null;return (@@ -214,7 +232,7 @@ function ConnectorGuideView({ connector: c, openUrl, back, next }: ConnectorGuid<button type="button" onClick={back}>Back</button>- <button type="button" className="primary" onClick={next}>+ <button type="button" className="primary" disabled={!canChange} onClick={next}>Continue</button></div>@@ -259,7 +277,8 @@ function AddAnother({ ask, cancel }: { ask: (what: string) => void; cancel: () =interface ImportListProps {found: ImportCandidate[];- importServers: (ids: string[]) => void;+ /** Missing outside the desktop app: the list reads, but nothing can be imported. */+ importServers?: (ids: string[]) => void;close: () => void;}@@ -317,8 +336,8 @@ function ImportList({ found, importServers, close }: ImportListProps) {<buttontype="button"className="primary"- disabled={count === 0}- onClick={() => importServers(chosen)}+ disabled={count === 0 || !importServers}+ onClick={() => importServers?.(chosen)}>{count === 0 ? "Import" : `Import ${count} server${count === 1 ? "" : "s"}`}</button>@@ -347,13 +366,15 @@ function ImportNames({ label, names }: { label: string; names: string[] }) {interface ConnectorRowProps {connector: ConnectorInfo;- send: Send;+ /** Missing outside the desktop app: every control is disabled. */+ appSend?: Send;connect: () => void;signIn: () => void;setUp: () => void;}-function ConnectorRow({ connector: c, send, connect, signIn, setUp }: ConnectorRowProps) {+function ConnectorRow({ connector: c, appSend, connect, signIn, setUp }: ConnectorRowProps) {+ const locked = !appSend;const nameId = `connector-${c.id}`;const readOnlyNote = c.custom? "Its tools stay hidden until you choose Read and send. Then it asks you before every action."@@ -387,7 +408,8 @@ function ConnectorRow({ connector: c, send, connect, signIn, setUp }: ConnectorRtype="radio"name={`mode-${c.id}`}checked={c.mode === mode}- onChange={() => send({ type: "connector_mode", connectorId: c.id, mode })}+ disabled={locked}+ onChange={() => appSend?.({ type: "connector_mode", connectorId: c.id, mode })}/>{label}</label>@@ -396,22 +418,40 @@ function ConnectorRow({ connector: c, send, connect, signIn, setUp }: ConnectorR) : null}<div className="provider-actions">{c.enabled ? null : (- <button type="button" className="primary" aria-label={`Connect ${c.name}`} onClick={connect}>+ <button+ type="button"+ className="primary"+ aria-label={`Connect ${c.name}`}+ disabled={locked}+ onClick={connect}+ >Connect</button>)}{c.enabled && c.status === "needs_setup" ? (- <button type="button" className="primary" aria-label={`Set up ${c.name}`} onClick={setUp}>+ <button+ type="button"+ className="primary"+ aria-label={`Set up ${c.name}`}+ disabled={locked}+ onClick={setUp}+ >Set up</button>) : null}{canSignIn && c.status !== "connected" ? (- <button type="button" className="primary" aria-label={`Sign in to ${c.name}`} onClick={signIn}>+ <button+ type="button"+ className="primary"+ aria-label={`Sign in to ${c.name}`}+ disabled={locked}+ onClick={signIn}+ >Sign in</button>) : null}{canSignIn && c.status === "connected" ? (- <button type="button" aria-label={`Sign in to ${c.name} again`} onClick={signIn}>+ <button type="button" aria-label={`Sign in to ${c.name} again`} disabled={locked} onClick={signIn}>Sign in again</button>) : null}@@ -419,7 +459,8 @@ function ConnectorRow({ connector: c, send, connect, signIn, setUp }: ConnectorR<buttontype="button"aria-label={`Disconnect ${c.name}`}- onClick={() => send({ type: "connector_disconnect", connectorId: c.id })}+ disabled={locked}+ onClick={() => appSend?.({ type: "connector_disconnect", connectorId: c.id })}>Disconnect</button>@@ -429,7 +470,8 @@ function ConnectorRow({ connector: c, send, connect, signIn, setUp }: ConnectorRtype="button"className="link"aria-label={`Remove ${c.name}`}- onClick={() => send({ type: "connector_remove", connectorId: c.id })}+ disabled={locked}+ onClick={() => appSend?.({ type: "connector_remove", connectorId: c.id })}>Remove</button>diff --git a/packages/ui/src/desktop.ts b/packages/ui/src/desktop.tsindex 7b8d119..ba67203 100644--- a/packages/ui/src/desktop.ts+++ b/packages/ui/src/desktop.ts@@ -1,4 +1,4 @@-import type { AgentState } from "@gentle-dot/protocol";+import type { AgentState, ClientMessage } from "@gentle-dot/protocol";import { invoke, isTauri } from "@tauri-apps/api/core";import type { ConnectionInfo } from "./client.ts";@@ -9,6 +9,14 @@ export function connectionInfo(): Promise<ConnectionInfo> {return invoke<ConnectionInfo>("connection_info");}+/**+ * A connector change from the panel (S25.2): the app sends it to the daemon over its private+ * channel, on behalf of this window (`clientId`, from `ready`). Rejects with the app's reason.+ */+export function connectorCommand(clientId: string, message: ClientMessage): Promise<void> {+ return invoke<void>("connector_command", { clientId, message });+}+export function togglePanel(): void {void invoke("toggle_panel");}diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.tsindex 5e00437..06780d4 100644--- a/packages/ui/src/store.ts+++ b/packages/ui/src/store.ts@@ -80,6 +80,8 @@ export interface ModelsState {/** Errors about the picker's choice show in the picker, not as a notice. */const MODEL_ERRORS = new Set(["model_unavailable", "thinking_unavailable", "model_switch_failed"]);+/** A connector change that did not happen: the app declined it, or there is no app to make it. */+const CONNECTOR_REFUSALS = new Set(["declined", "app_required"]);/** The daemon's answer to a voice request, matched by `requestId`. */export type VoiceReply = Extract<@@ -112,6 +114,8 @@ export interface Notice {export interface DotState {connection: ConnectionStatus;agentState: AgentState;+ /** This window's id for the desktop app's connector commands on its behalf (S25.2). */+ clientId?: string;conversationId?: string;model?: string;features: Features;@@ -144,7 +148,8 @@ export type DotAction =| { type: "connector_started"; connectorId: string }| { type: "connector_imports_closed" }| { type: "models_opened" }- | { type: "auth_started"; providerId: string };+ | { type: "auth_started"; providerId: string }+ | { type: "notice"; level: Notice["level"]; message: string };export const initialState: DotState = {connection: "connecting",@@ -209,6 +214,8 @@ export function reduce(state: DotState, action: DotAction): DotState {...state,auth: { ...state.auth, open: true, flow: { providerId: action.providerId, events: [] } },};+ case "notice":+ return addNotice(state, action.level, action.message);case "server":return reduceServer(state, action.message);}@@ -220,6 +227,7 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {return {...state,agentState: message.agentState,+ ...(message.clientId ? { clientId: message.clientId } : {}),// The daemon sends the queue right after ready when one exists.queue: initialState.queue,conversationId: message.conversationId ?? state.conversationId,@@ -378,10 +386,18 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {}case "toast":return addNotice(state, message.level, message.message);- case "error":+ case "error": {if (MODEL_ERRORS.has(message.code))return { ...state, models: { ...state.models, error: message.message } };- return addNotice(state, "error", message.message);+ // A sign-in that was only starting never began: back to the list.+ const flow = state.connectors.flow;+ const starting = flow !== undefined && flow.flowId === undefined && flow.events.length === 0;+ const next =+ CONNECTOR_REFUSALS.has(message.code) && starting+ ? { ...state, connectors: { ...state.connectors, flow: undefined } }+ : state;+ return addNotice(next, "error", message.message);+ }}}diff --git a/packages/ui/src/useComputer.ts b/packages/ui/src/useComputer.tsindex df34f73..dba3548 100644--- a/packages/ui/src/useComputer.ts+++ b/packages/ui/src/useComputer.ts@@ -1,4 +1,3 @@-import type { ClientMessage } from "@gentle-dot/protocol";import { useEffect, useState } from "react";import { type ComputerState, computerEndpoint, computerStatus, onComputerState } from "./computer.ts";@@ -22,14 +21,10 @@ export function useComputerState(enabled: boolean): ComputerState {}/**- * Registers the app's helper with the daemon on every connection (S24.7); the daemon drops it when- * this window disconnects. True when the app has a helper. The key is passed on, never kept.+ * Whether the app has a computer-control helper (S24.7). The app itself registers it with the daemon+ * it launched, over its private channel (L61); the window never sends its key.*/-export function useComputerRegistration(- enabled: boolean,- connected: boolean,- send: (message: ClientMessage) => void,-): boolean {+export function useComputerAvailable(enabled: boolean, connected: boolean): boolean {const [available, setAvailable] = useState(false);useEffect(() => {if (!enabled || !connected) return;@@ -38,7 +33,6 @@ export function useComputerRegistration((endpoint) => {if (!live) return;setAvailable(endpoint !== null);- if (endpoint) send({ type: "computer_register", url: endpoint.url, token: endpoint.token });},() => {if (live) setAvailable(false);@@ -47,6 +41,6 @@ export function useComputerRegistration(return () => {live = false;};- }, [enabled, connected, send]);+ }, [enabled, connected]);return available;}diff --git a/packages/ui/test/computer.test.tsx b/packages/ui/test/computer.test.tsxindex 247b779..189b283 100644--- a/packages/ui/test/computer.test.tsx+++ b/packages/ui/test/computer.test.tsx@@ -1,6 +1,6 @@import { readFileSync } from "node:fs";import { fileURLToPath } from "node:url";-import type { ConnectorInfo } from "@gentle-dot/protocol";+import { APP_REQUIRED, type ConnectorInfo } from "@gentle-dot/protocol";import { act, render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -119,19 +119,20 @@ afterEach(() => {window.sessionStorage.clear();});-describe("registering the helper (S24.7)", () => {- it("the desktop panel asks the app for the endpoint once connected and registers it with the daemon", async () => {+describe("registering the helper (S24.7, L61)", () => {+ it("the desktop panel only asks the app whether it has a helper; the app registers it over its channel", async () => {h.state = { ...h.state, connection: "connecting" };const view = await renderApp("?surface=panel");await new Promise((resolve) => setTimeout(resolve, 20));expect(invoked("computer_endpoint")).toHaveLength(0);- h.state = { ...h.state, connection: "open" };+ h.state = { ...connectorsOpen([notion, computerEntry()]), connection: "open" };const { App } = await import("../src/App.tsx");view.rerender(<App />);- await waitFor(() => expect(registrations()).toHaveLength(1));- expect(registrations()[0]?.[0]).toEqual({ type: "computer_register", url: HELPER, token: KEY });- expect(invoked("computer_endpoint")).toHaveLength(1);+ await waitFor(() => expect(invoked("computer_endpoint")).toHaveLength(1));+ await screen.findByRole("listitem", { name: "Computer" });+ expect(registrations()).toHaveLength(0);+ expect(JSON.stringify(h.send.mock.calls)).not.toContain(KEY);});it("registers nothing when the app has no helper", async () => {@@ -339,3 +340,28 @@ describe("yolo mode (S24.9)", () => {expect(rule('.switch[aria-checked="true"]')).toMatch(/var\(--accent/);});});++describe("connector changes go through the app (S25.2)", () => {+ it("the panel sends them with its window's id to the app, never over the WebSocket", async () => {+ h.state = { ...connectorsOpen([notion]), clientId: "window-1" };+ await renderApp("?surface=panel");+ const entry = within(await screen.findByRole("listitem", { name: "Notion" }));+ await userEvent.setup().click(entry.getByRole("button", { name: "Disconnect Notion" }));+ await waitFor(() => expect(invoked("connector_command")).toHaveLength(1));+ expect(invoked("connector_command")[0]?.[1]).toEqual({+ clientId: "window-1",+ message: { type: "connector_disconnect", connectorId: "notion" },+ });+ expect(h.send.mock.calls.some(([m]) => m.type === "connector_disconnect")).toBe(false);+ });++ it("the web page shows them disabled with the reason", async () => {+ h.tauri = false;+ h.state = { ...connectorsOpen([notion]), clientId: "window-1" };+ await renderApp("?#token=web-key");+ const entry = within(await screen.findByRole("listitem", { name: "Notion" }));+ expect(entry.getByRole("button", { name: "Disconnect Notion" })).toBeDisabled();+ expect(screen.getByText(APP_REQUIRED)).toBeInTheDocument();+ expect(h.invoke).not.toHaveBeenCalled();+ });+});diff --git a/packages/ui/test/connectors-more.test.tsx b/packages/ui/test/connectors-more.test.tsxindex a0c514b..9f965a6 100644--- a/packages/ui/test/connectors-more.test.tsx+++ b/packages/ui/test/connectors-more.test.tsx@@ -1,10 +1,11 @@-import type {- ClientMessage,- ConnectorDraft,- ConnectorInfo,- ImportCandidate,- ServerMessage,- ServerPayload,+import {+ APP_REQUIRED,+ type ClientMessage,+ type ConnectorDraft,+ type ConnectorInfo,+ type ImportCandidate,+ type ServerMessage,+ type ServerPayload,} from "@gentle-dot/protocol";import { render, screen, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";@@ -143,14 +144,37 @@ const ready = apply(function Harness({ initial, send }: { initial: DotState; send: (m: ClientMessage) => void }) {const [state, dispatch] = useReducer(reduce, initial);- return <ChatSurface variant="panel" state={state} send={send} dismiss={vi.fn()} dispatch={dispatch} />;+ return (+ <ChatSurface+ variant="panel"+ state={state}+ send={send}+ appSend={send}+ dismiss={vi.fn()}+ dispatch={dispatch}+ />+ );+}++/** The web page: no app, so no `appSend`. */+function WebHarness({ initial, send }: { initial: DotState; send: (m: ClientMessage) => void }) {+ const [state, dispatch] = useReducer(reduce, initial);+ return <ChatSurface variant="web" state={state} send={send} dismiss={vi.fn()} dispatch={dispatch} />;}function panel(state: DotState) {const send = vi.fn();const dispatch = vi.fn();const openUrl = vi.fn();- render(<ConnectorsPanel connectors={state.connectors} send={send} dispatch={dispatch} openUrl={openUrl} />);+ render(+ <ConnectorsPanel+ connectors={state.connectors}+ send={send}+ appSend={send}+ dispatch={dispatch}+ openUrl={openUrl}+ />,+ );return { send, dispatch, openUrl };}@@ -341,3 +365,34 @@ describe("importing MCP servers", () => {expect(s.notices.at(-1)?.message).toMatch(/Imported stripe/);});});++describe("drafts and imports outside the desktop app (S25.2)", () => {+ it("a draft can be declined on the web page but only added in the app", async () => {+ const send = vi.fn();+ render(<WebHarness initial={apply(ready, { type: "connector_draft", draft })} send={send} />);+ const card = within(screen.getByRole("region", { name: "Add GitHub?" }));+ expect(card.getByRole("button", { name: "Add GitHub" })).toBeDisabled();+ expect(card.getByText(APP_REQUIRED)).toBeInTheDocument();+ await userEvent.setup().click(card.getByRole("button", { name: "Decline" }));+ expect(send.mock.calls.map(([m]) => m)).toEqual([+ { type: "connector_draft_reply", draftId: "d1", approve: false },+ ]);+ });++ it("the web page lists what it found but cannot import it", async () => {+ const send = vi.fn();+ render(+ <WebHarness+ initial={apply(reduce(ready, { type: "connectors", open: true }), {+ type: "connector_imports",+ found,+ })}+ send={send}+ />,+ );+ const list = within(screen.getByRole("region", { name: "Found these servers" }));+ await userEvent.setup().click(list.getByRole("checkbox", { name: "stripe" }));+ expect(list.getByRole("button", { name: /Import/ })).toBeDisabled();+ expect(send).not.toHaveBeenCalledWith(expect.objectContaining({ type: "connector_import" }));+ });+});diff --git a/packages/ui/test/connectors.test.tsx b/packages/ui/test/connectors.test.tsxindex 0197678..84e5e95 100644--- a/packages/ui/test/connectors.test.tsx+++ b/packages/ui/test/connectors.test.tsx@@ -1,6 +1,12 @@import { readFileSync } from "node:fs";import { fileURLToPath } from "node:url";-import type { ClientMessage, ConnectorInfo, ServerMessage, ServerPayload } from "@gentle-dot/protocol";+import {+ APP_REQUIRED,+ type ClientMessage,+ type ConnectorInfo,+ type ServerMessage,+ type ServerPayload,+} from "@gentle-dot/protocol";import { render, screen, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { useReducer } from "react";@@ -95,8 +101,15 @@ describe("ConnectorsPanel", () => {const send = vi.fn();const dispatch = vi.fn();const openUrl = vi.fn();+ // In the desktop panel connector changes go to the app (S25.2); both are the same mock here.render(- <ConnectorsPanel connectors={state.connectors} send={send} dispatch={dispatch} openUrl={openUrl} />,+ <ConnectorsPanel+ connectors={state.connectors}+ send={send}+ appSend={send}+ dispatch={dispatch}+ openUrl={openUrl}+ />,);return { send, dispatch, openUrl };}@@ -192,7 +205,16 @@ describe("ConnectorsPanel", () => {function Harness({ initial, send }: { initial: DotState; send: (m: ClientMessage) => void }) {const [state, dispatch] = useReducer(reduce, initial);- return <ChatSurface variant="panel" state={state} send={send} dismiss={vi.fn()} dispatch={dispatch} />;+ return (+ <ChatSurface+ variant="panel"+ state={state}+ send={send}+ appSend={send}+ dismiss={vi.fn()}+ dispatch={dispatch}+ />+ );}describe("Connectors in the panel", () => {@@ -247,3 +269,62 @@ describe("approval cards", () => {expect(rule).toMatch(/color: var\(--text\)/);});});++describe("connector changes outside the desktop app (S25.2)", () => {+ it("are shown disabled with the reason, and nothing is sent", async () => {+ const send = vi.fn();+ render(+ <ConnectorsPanel+ connectors={apply(ready, { type: "connectors", connectors: list, open: true }).connectors}+ send={send}+ dispatch={vi.fn()}+ openUrl={vi.fn()}+ />,+ );+ expect(screen.getByText(APP_REQUIRED)).toBeInTheDocument();+ const notion = within(screen.getByRole("listitem", { name: "Notion" }));+ for (const radio of notion.getAllByRole("radio")) expect(radio).toBeDisabled();+ for (const name of ["Sign in to Notion again", "Disconnect Notion", "Remove Notion"])+ expect(notion.getByRole("button", { name })).toBeDisabled();+ const linear = within(screen.getByRole("listitem", { name: "Linear" }));+ expect(linear.getByRole("button", { name: "Sign in to Linear" })).toBeDisabled();+ const atlassian = within(screen.getByRole("listitem", { name: "Atlassian" }));+ await userEvent.setup().click(atlassian.getByRole("button", { name: "Connect Atlassian" }));+ expect(send).not.toHaveBeenCalled();+ // Reading stays available.+ expect(screen.getByRole("button", { name: "Import my MCP servers" })).toBeEnabled();+ });++ it("an approval the app asks natively shows only that it waits there", () => {+ render(+ <AskCard+ ask={{+ requestId: "app-1",+ method: "app",+ title: "Allow Notion to create pages?",+ message: "Waiting for your answer in the Gentle Dot app.",+ }}+ send={vi.fn()}+ />,+ );+ expect(screen.getByText("Allow Notion to create pages?")).toBeInTheDocument();+ expect(screen.getByText("Waiting for your answer in the Gentle Dot app.")).toBeInTheDocument();+ expect(screen.queryByRole("button")).toBeNull();+ });+});++describe("the window's id for the app's commands", () => {+ it("comes with ready, and a refused change drops the sign-in that was starting", () => {+ let s = apply(ready, { type: "ready", agentState: "idle", clientId: "window-1" });+ expect(s.clientId).toBe("window-1");+ s = apply(s, { type: "connectors", connectors: list, open: true });+ s = reduce(s, { type: "connector_started", connectorId: "atlassian" });+ s = apply(s, { type: "error", code: "declined", message: "Nothing was changed." });+ expect(s.connectors.flow).toBeUndefined();+ expect(s.connectors.open).toBe(true);+ expect(s.notices.at(-1)?.message).toBe("Nothing was changed.");+ s = reduce(s, { type: "connector_started", connectorId: "atlassian" });+ s = apply(s, { type: "error", code: "app_required", message: APP_REQUIRED });+ expect(s.connectors.flow).toBeUndefined();+ });+});