Skip to content

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

TypeScript

fix(approvals): refuse an Allow given after the deadline

Marcelitod7b00a004c02
diff --git a/apps/desktop/src-tauri/src/approvals/mod.rs b/apps/desktop/src-tauri/src/approvals/mod.rs
index adef67e..065c305 100644
--- a/apps/desktop/src-tauri/src/approvals/mod.rs
+++ b/apps/desktop/src-tauri/src/approvals/mod.rs
@@ -199,27 +199,45 @@ impl Approvals {
/// Asks the user. Blocks until the answer or the timeout, so call it off the main thread.
pub fn confirm(&self, request: &ApprovalRequest) -> Decision {
+ match self.show(request) {
+ Some(shown) => self.wait(shown),
+ None => Decision::Declined,
+ }
+ }
+
+ /// Waits for the screen and puts the dialog up; `None` when it cannot show in time.
+ fn show(&self, request: &ApprovalRequest) -> Option<Shown> {
let deadline = Instant::now() + self.timeout;
let dialog = ApprovalDialog { deadline: Some(deadline), ..ApprovalDialog::new(request, self.timeout) };
- let Some(ticket) = self.gate.acquire(deadline) else {
- return Decision::Declined;
- };
+ let ticket = self.gate.acquire(deadline)?;
// The dialog runs on a thread of its own that holds the screen until the dialog closes,
// so a stale dialog left after the timeout still keeps the next one waiting.
let (answer, answered) = mpsc::channel();
let (prompt, gate) = (self.prompt.clone(), self.gate.clone());
let spawned = std::thread::Builder::new().name("approval-dialog".into()).spawn(move || {
let _screen = Ticket { gate, ticket };
- let _ = answer.send(prompt.ask(&dialog));
+ let allowed = prompt.ask(&dialog);
+ let _ = answer.send(Answered { allowed, at: Instant::now() });
});
if spawned.is_err() {
self.gate.release(ticket);
- return Decision::Declined;
+ return None;
}
+ Some(Shown { ticket, deadline, answered })
+ }
+
+ /// Waits for the answer of a dialog on screen until its deadline.
+ fn wait(&self, shown: Shown) -> Decision {
+ let Shown { ticket, deadline, answered } = shown;
match answered.recv_timeout(deadline.saturating_duration_since(Instant::now())) {
- Ok(true) => Decision::Approved,
- // Declined, or the dialog failed (its thread panicked).
- Ok(false) | Err(RecvTimeoutError::Disconnected) => Decision::Declined,
+ // An Allow counts only when given before the deadline. `recv_timeout` still returns
+ // an answer already queued when this thread looks late (it was descheduled), so the
+ // time comes from the dialog's thread, stamped when the dialog returned: never earlier
+ // than the click, so any delay there refuses.
+ Ok(Answered { allowed: true, at }) if at < deadline => Decision::Approved,
+ // Declined, given too late (the dialog has closed: nothing to dismiss), or the dialog
+ // failed (its thread panicked).
+ Ok(_) | Err(RecvTimeoutError::Disconnected) => Decision::Declined,
Err(RecvTimeoutError::Timeout) => {
self.gate.while_held(ticket, || self.prompt.dismiss());
Decision::Declined
@@ -228,6 +246,20 @@ impl Approvals {
}
}
+/// A dialog [`Approvals::show`] put up: its turn on the screen, its deadline, and where its
+/// answer arrives.
+struct Shown {
+ ticket: u64,
+ deadline: Instant,
+ answered: mpsc::Receiver<Answered>,
+}
+
+/// The user's answer and when the dialog gave it.
+struct Answered {
+ allowed: bool,
+ at: Instant,
+}
+
/// Who holds the screen: at most one dialog, identified by a ticket.
#[derive(Default)]
struct Gate {
diff --git a/apps/desktop/src-tauri/src/approvals/tests.rs b/apps/desktop/src-tauri/src/approvals/tests.rs
index 9aca16b..9c035ca 100644
--- a/apps/desktop/src-tauri/src/approvals/tests.rs
+++ b/apps/desktop/src-tauri/src/approvals/tests.rs
@@ -148,6 +148,35 @@ fn a_late_click_on_a_stale_dialog_approves_nothing() {
assert_eq!(prompt.shown_titles().len(), 2);
}
+/// Returns once the dialog's thread has ended; it frees the screen only after sending its answer.
+fn wait_until_answered(approvals: &Approvals) {
+ let ticket = approvals.gate.acquire(Instant::now() + LONG).expect("the dialog closed");
+ approvals.gate.release(ticket);
+}
+
+#[test]
+fn an_allow_given_after_the_deadline_is_declined_even_when_already_waiting() {
+ // A descheduled receiver: it only looks once the late Allow is queued, and the deadline gone.
+ let timeout = Duration::from_millis(50);
+ let prompt = Arc::new(FakePrompt::new([Answer::After(timeout * 2, true)]));
+ let approvals = approvals(&prompt, timeout);
+ let shown = approvals.show(&request(vec![])).expect("shown");
+ wait_until_answered(&approvals);
+ assert_eq!(approvals.wait(shown), Decision::Declined);
+ assert_eq!(prompt.dismissals(), 0, "the dialog had already closed");
+}
+
+#[test]
+fn an_allow_given_in_time_counts_even_when_seen_after_the_deadline() {
+ let timeout = Duration::from_millis(500);
+ let prompt = Arc::new(FakePrompt::new([Answer::After(Duration::ZERO, true)]));
+ let approvals = approvals(&prompt, timeout);
+ let shown = approvals.show(&request(vec![])).expect("shown");
+ wait_until_answered(&approvals);
+ std::thread::sleep(timeout + Duration::from_millis(100));
+ assert_eq!(approvals.wait(shown), Decision::Approved);
+}
+
#[test]
fn only_one_dialog_shows_at_a_time() {
let hold = Duration::from_millis(40);
diff --git a/docs/design.md b/docs/design.md
index 5835bd2..d68be93 100644
--- a/docs/design.md
+++ b/docs/design.md
@@ -142,7 +142,7 @@ 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 (no curated list, so the proxy shows none, and 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. `connectors.json` can hold a server of the user's own (a command), so it is signed (Integrity, below): with the app, a file edited while the daemon is not running is set aside instead of loaded.
- 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, read only with every tool hidden, and never touches the source files; their header and environment values go to the app's secure store (below, Secrets), with references in `connectors.json`. A credential inside an imported address or command-line argument stays where it is (masked when shown; a documented limit).
- 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` and `<agentHome>/mcp.json`, both rendered from memory, atomically, mode 0600; neither holds a secret. 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." A change made to `connectors.json` while the daemon is not running is caught by its signature at the next start with the app (Integrity, below); `mcp.json` is always rewritten from memory. Every server is `exposure: "direct"` (the assistant turns codemode off). Read only is enforced by the proxy (above).
-- 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).
+- 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. An Allow given after the app's 120 s is refused too, even when the app only reads it later. 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).
- Secrets (S25.5, `packages/daemon/src/secret-source.ts`): bot tokens, client secrets, imported header and environment values, and OAuth sign-ins live in the desktop app's secure store (macOS: Keychain items the signed app creates, service `dev.gentleman.gentle-dot.connectors`; `apps/desktop/src-tauri/src/secure_store`). The daemon asks for them over the app channel (`secret_get`, `secret_put`, `secret_delete`, `secret_list`, below) and keeps them in memory only, until the channel closes; no secret is written to a file or a log. `connectors.json` holds `{"secretRef": "<id>"}` in each secret's place, with ids `connector/<id>/value/<key>`, `connector/<id>/env/<NAME>`, `connector/<id>/header/<Name>`, `connector/<id>/client-secret`, and `connector/<id>/signin` (pi-mcp's OAuth state as JSON). In a server of the user's own, every environment value, header, and `oauth.clientSecret` is treated as a secret unless it only names a typed field. Before the proxy uses a connector it reads the secrets it refers to; the daemon only reads ids it recorded after its own `put`. Without the app (a daemon started from a terminal such as `pnpm dev`, the web), a connector that needs a secret fails closed with "Open the Gentle Dot app to use this connector." (the proxy answers it to every request), and a connector without secrets keeps working; there is no file fallback. Removing a connector deletes its items.
- Migration (once, when the app's channel is there): text secrets still in `connectors.json`, then the sign-ins of the old sign-in home (`<data>/connector-signin/mcp-auth.json`, the daemon's own, which win) and of the engine's old `<agentHome>/mcp-auth.json` (keyed `mcp__<id>|<url>`), are stored, read back, and compared before they leave the files; if one fails, the files stay as they were and the next start tries again. A sign-in for a connector that is no longer added is dropped (counted in the log). The old sign-in home (its `mcp.json` held the real servers) is removed. A 0-byte sign-in file holds nothing: it is removed and the removal is logged. One that cannot be read or is not a list of sign-ins may hold secrets: it is left as it is and reported, the other files still move, and the migration is not marked done, so the next start tries again (L117 A2). `connectors.json` then says `version: 2`, and a sign-in file that appears afterwards is reported once and left alone, never imported (L114 N1). Until a text secret has moved it stays in the file and is not used. Nothing secret is logged.
- Integrity (S25.6, `packages/daemon/src/connector-integrity.ts`): every write of `connectors.json` (a change, a migration, a put-back) carries `mac`, the lowercase hex HMAC-SHA256 of the text `gentle-dot/connectors.json/v1\n` followed by the record without `mac` in canonical JSON (no whitespace; every object's keys sorted by UTF-16 code unit; arrays in order; strings, numbers, booleans, and null as `JSON.stringify` writes them). The key is 32 random bytes, kept as hex in the app's secure store under `integrity/connectors`, created on the first start with the app, and held only in memory; it is never written to a file or logged. At start the daemon listens (so the app's health check answers), then checks the file as it was read before anything rewrites it, watches it, migrates secrets, answers the app, or starts the engine. With the app: a file that was signed before (it has a `mac`, or the key already existed) whose `mac` is missing or wrong was changed while Gentle Dot was closed; it is moved to `<data>/connectors.rejected-<UTC time>.json` (0600; a planted link is moved as a link), the daemon starts with no connectors and a fresh signed record, the log says so once, and every window of that run gets the warning toast "Connectors were changed while Gentle Dot was closed, so they were set aside. Review them in Connectors." The Keychain items are not touched (a reference in the set-aside file is never read). The first start after T23e (an unsigned file and no key) creates the key and signs the file without refusing it. Without the app, the file cannot be checked: it is loaded as it is, the log says it was not verified, connectors that need a secret stay locked, and a signed file is put back byte for byte so its signature survives until a daemon the app launches checks it. With the app but a key that cannot be read or stored, the check fails closed: the file stays as it is, no secret is read, and every window gets "Gentle Dot could not check your connectors, so the ones that need a secret stay locked. Restart Gentle Dot to try again." A signed file deleted while Gentle Dot was closed (the key exists, the file is gone) starts with no connectors and every window gets "Your connectors file was removed while Gentle Dot was closed. Add your connectors again in Connectors." While running, a change is put back as before, signed. Limits: the signature has no counter, so putting back an older signed version of the file (for example one with a connector the user removed since) is accepted; sending actions still need the user's native approval. A same-user process that deletes the key's Keychain item and also removes `mac` makes the next start sign the file as a first start. A `connectors.json` written without the app (a migration rename of a `computer` entry) is unsigned and is refused at the next start with the app once the key exists; the key's Keychain item has the same limits as any other (§8).