A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
feat: connectors core with one-click Notion, Linear, and Atlassian sign-in and an approval guard for outward actions
Alan Buscagliae49bd9d9f056
diff --git a/README.md b/README.mdindex 5f0485d..c153f7e 100644--- a/README.md+++ b/README.md@@ -39,6 +39,8 @@ The assistant keeps to its own instance. The agent works in `~/.gentle-dot/worksMemory uses your global Engram (`~/.engram`, server on port 7437, or your own `ENGRAM_DATA_DIR`, `ENGRAM_PORT`, and `ENGRAM_URL`), and everything the assistant remembers goes to the project `gentle-dot`. If Engram is not running, the assistant starts it with your data folder. `GENTLE_DOT_ENGRAM_DATA_DIR` points at another data folder; `GENTLE_DOT_ENGRAM=private` gives the assistant a memory of its own instead (port 7438, `GENTLE_DOT_ENGRAM_PORT`). Memories saved by earlier versions in `~/.gentle-dot/home/.engram` are not moved to the global Engram.+Connectors let the assistant use Notion, Linear, and Atlassian through their official MCP servers: open Connectors (the plug icon, or type `/connectors`), choose Connect, and approve access in the browser. Each connector is "Read only" (it can search and read) or "Read and send"; even then, the assistant asks you with a preview before every action that sends or changes something. The daemon alone writes the engine's `mcp.json` (`~/.gentle-dot/agent`) from `~/.gentle-dot/connectors.json` and puts it back if anything else changed it.+## Checks```bashdiff --git a/apps/desktop/src-tauri/src/shell.rs b/apps/desktop/src-tauri/src/shell.rsindex 514cff8..2993633 100644--- a/apps/desktop/src-tauri/src/shell.rs+++ b/apps/desktop/src-tauri/src/shell.rs@@ -228,24 +228,49 @@ fn build_windows(app: &AppHandle, config: &DesktopConfig) -> tauri::Result<()> {Ok(())}+/// Whether the conversations list is on, read like the daemon reads it (`GENTLE_DOT_CONVERSATIONS=1`).+fn conversations_on(value: Option<&str>) -> bool {+ value == Some("1")+}++/// The tray menu, top to bottom (`-` is a separator). "New conversation" only exists with the+/// conversations list on; in the single continuous chat there is nothing new to start.+fn tray_menu_ids(conversations: bool) -> Vec<&'static str> {+ let mut ids = vec!["open"];+ if conversations {+ ids.push("new");+ }+ ids.extend(["browser", "-", "restart", "autostart", "-", "quit"]);+ ids+}+fn build_tray(app: &AppHandle, config: &DesktopConfig) -> tauri::Result<TrayIcon> {let autostart = app.autolaunch().is_enabled().unwrap_or(false);// The accelerator is only a label here; an unparsable one must not break the menu.let open = MenuItem::with_id(app, "open", "Open", true, Some(config.shortcut.as_str())).or_else(|_| MenuItem::with_id(app, "open", "Open", true, None::<&str>))?;- let menu = Menu::with_items(- app,- &[- &open,- &MenuItem::with_id(app, "new", "New conversation", true, None::<&str>)?,- &MenuItem::with_id(app, "browser", "Open in browser", true, None::<&str>)?,- &PredefinedMenuItem::separator(app)?,- &MenuItem::with_id(app, "restart", "Restart assistant", true, None::<&str>)?,- &CheckMenuItem::with_id(app, "autostart", "Launch at login", true, autostart, None::<&str>)?,- &PredefinedMenuItem::separator(app)?,- &MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?,- ],- )?;+ let menu = Menu::new(app)?;+ let conversations = conversations_on(std::env::var("GENTLE_DOT_CONVERSATIONS").ok().as_deref());+ for id in tray_menu_ids(conversations) {+ match id {+ "open" => menu.append(&open)?,+ "new" => menu.append(&MenuItem::with_id(app, "new", "New conversation", true, None::<&str>)?)?,+ "browser" => menu.append(&MenuItem::with_id(app, "browser", "Open in browser", true, None::<&str>)?)?,+ "restart" => {+ menu.append(&MenuItem::with_id(app, "restart", "Restart assistant", true, None::<&str>)?)?;+ }+ "autostart" => menu.append(&CheckMenuItem::with_id(+ app,+ "autostart",+ "Launch at login",+ true,+ autostart,+ None::<&str>,+ )?)?,+ "quit" => menu.append(&MenuItem::with_id(app, "quit", "Quit", true, None::<&str>)?)?,+ _ => menu.append(&PredefinedMenuItem::separator(app)?)?,+ }+ }TrayIconBuilder::with_id(TRAY).icon(Image::from_bytes(TrayGlyph::Unavailable.png())?).icon_as_template(true)@@ -371,3 +396,32 @@ pub fn run() {}});}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn tray_hides_new_conversation_in_the_single_chat() {+ assert_eq!(+ tray_menu_ids(false),+ vec!["open", "browser", "-", "restart", "autostart", "-", "quit"]+ );+ }++ #[test]+ fn tray_shows_new_conversation_with_the_conversations_list() {+ assert_eq!(+ tray_menu_ids(true),+ vec!["open", "new", "browser", "-", "restart", "autostart", "-", "quit"]+ );+ }++ #[test]+ fn conversations_flag_reads_like_the_daemon() {+ assert!(conversations_on(Some("1")));+ assert!(!conversations_on(None));+ assert!(!conversations_on(Some("0")));+ assert!(!conversations_on(Some("true")));+ }+}diff --git a/docs/design.md b/docs/design.mdindex fb48bca..0094456 100644--- a/docs/design.md+++ b/docs/design.md@@ -64,6 +64,7 @@ docs/ design, deployment guide, security checklist- Spawns the bundled engine (`node <gentle-pi>/bin/gentle-shell.mjs --home <dataDir>/agent --mode rpc --session-dir <dataDir>/sessions --append-system-prompt <identity file>`) with `cwd` = the assistant's own workspace, `<dataDir>/workspace`, so the engine never reads a `.pi` project config from the user's home. A custom `workspace` (config or `GENTLE_DOT_WORKSPACE`) is never used as `cwd` and nothing is written there; it is passed as one more `--append-system-prompt` text: "The user's preferred working folder is <path>. Use absolute paths there unless told otherwise."- Isolation (S12): the child runs with its own `HOME=<dataDir>/home` (0700) and `XDG_CONFIG_HOME`, `XDG_DATA_HOME`, `XDG_CACHE_HOME`, and `XDG_STATE_HOME` under it, plus `GENTLE_PI_CONFIG_HOME=<dataDir>/gentle-ai`. `PATH` is kept, and `GIT_CONFIG_GLOBAL` points at the user's real `~/.gitconfig` when it exists, to keep their git identity. Inherited `PI_CODING_AGENT_DIR`, `GENTLE_PI_AGENT_HOME`, and `GENTLE_SHELL_CONFIG` are removed. The engine's first run otherwise writes into the real `~` (`~/.gentle-shell`, `~/.pi/agent/pi-pretty`, `~/.gentle-ai`), which `--home` alone does not prevent.- Memory (S23): the engine uses the user's global Engram, always in the project `gentle-dot`. The memory plugin accepts a server only when `engram instance-id` (read from the Engram data folder, by default `$HOME/.engram`) matches the server's `/health` `instance_id`, so the child gets `ENGRAM_DATA_DIR=<real ~/.engram>` (the inherited `ENGRAM_DATA_DIR` when set; override `GENTLE_DOT_ENGRAM_DATA_DIR`) and keeps the user's own `ENGRAM_PORT` and `ENGRAM_URL` (default server 7437). If the global Engram is not running, the plugin starts it with that data folder, as Gentle Shell does. The project comes from Engram's per-folder setting: the daemon writes `<dataDir>/workspace/.engram/config.json` (`{"project_name":"gentle-dot"}`) at every start, and Engram reads it before any other detection (source `config`). The plugin has no per-client project override (`ENGRAM_PROJECT` only applies to the Engram process itself, which is the user's shared server). Memories the assistant saved earlier in its private memory (`<dataDir>/home/.engram`) are not moved. `GENTLE_DOT_ENGRAM=private` restores a private memory: no `ENGRAM_DATA_DIR`, `ENGRAM_URL` removed, `ENGRAM_PORT=7438` (override `GENTLE_DOT_ENGRAM_PORT`), data under `<dataDir>/home/.engram`.+- Connectors (S18): before every spawn (first start, restart, respawn) the supervisor's `prepareSpawn` hook checks `<agentHome>/mcp.json` against the hash in `<dataDir>/connectors.json` and restores it, then hands the approval guard its policy in the child's environment (`GENTLE_DOT_CONNECTOR_POLICY`, JSON: the turned-on connectors, their modes and curated read-only tools, and the protected files). The engine cannot change its own environment, so the policy cannot be edited by the assistant. The assistant's own engine loads the guard with `-e packages/daemon/src/extensions/approval-guard.ts` (TypeScript loads as is).- Parses stdout with strict LF framing on a byte stream. Never Node `readline` (it splits on U+2028/U+2029, which are valid inside JSON).- Correlates commands by `id`; stdout records without `id` are session events.- Reads stderr only as diagnostics (logged, never parsed).@@ -92,6 +93,12 @@ Client to daemon:| `auth_login` | `providerId`, `method` (`oauth` \| `api_key`) | daemon `ModelRuntime.login()`; one flow at a time || `auth_reply` | `flowId`, `value` \| `cancelled` | answers the flow's current prompt || `auth_logout` | `providerId` | daemon `ModelRuntime.logout()` |+| `connectors_list` | — | daemon `connectors.json` and `mcp-auth.json` key presence |+| `connector_connect` | `connectorId` | adds or turns on the connector (new `mcp.json`, agent restart when idle), then `mcp login` when not signed in |+| `connector_signin` | `connectorId` | `mcp login <id>`; one flow at a time |+| `connector_disconnect` | `connectorId` | turns it off (the sign-in stays); agent restart when idle |+| `connector_mode` | `connectorId`, `mode` (`read_only` \| `read_write`) | new `mcp.json`; agent restart when idle |+| `connector_remove` | `connectorId` | `mcp logout <id>`, then forgets it; agent restart when idle |Daemon to client:@@ -116,6 +123,7 @@ Daemon to client:| `auth_prompt` | `flowId`, `kind` (`text`, `secret`, `select`, `manual_code`), `message`, `options` — sent only to the window that started the flow || `auth_event` | `auth_url`, `device_code`, `progress`, or `info` || `auth_done` | `ok`, plain-language `message` on failure or cancellation |+| `connectors` | `connectors` (`id`, `name`, `reads`, `sends`, `added`, `enabled`, `mode`, `status`: `off` \| `needs_signin` \| `connected` \| `error`); `open: true` when the user typed `/connectors` |### Sign-in (S10) and own instance (S12)@@ -123,6 +131,14 @@ The daemon runs the Gentle Shell bundled as its `gentle-pi` dependency, with `--Every daemon message carries `seq` (monotonic per connection) so the UI can detect gaps and request `get_history`.+### Connectors (S18)++- Catalog (`packages/daemon/src/connectors.ts`): Notion `https://mcp.notion.com/mcp`, Linear `https://mcp.linear.app/mcp`, and Atlassian `https://mcp.atlassian.com/v2/mcp`, each remote OAuth, with a curated list of read-only tools. Slack, Gmail, Discord, assistant-drafted servers (S19), and imports (S20) add catalog entries or drafts that go through the same store.+- The daemon is the only writer of `<agentHome>/mcp.json`. It renders the file from `<dataDir>/connectors.json` (each connector's `enabled` and `mode`, plus the sha256 of the approved `mcp.json`), writes both atomically with mode 0600, and restores `mcp.json` before every agent start. Every server is `exposure: "direct"` (the assistant turns codemode off). "Read only" adds `toolExposure: {"*": "hidden", <curated tool>: "direct"}`; the engine prefers exact names over patterns, so an unknown tool stays hidden.+- 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=<agentHome>`. 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: `connected` when `mcp-auth.json` holds tokens under `mcp__<id>|<url>` (token values are dropped while parsing); `needs_signin` otherwise; `error` after a failed sign-in.+- Approval guard (`packages/daemon/src/extensions/approval-guard.ts`, `tool_call` hook, nested calls included): a connector tool 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 the key arguments, truncated), and 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. `write`/`edit` of `mcp.json`, `mcp-auth.json`, `connectors.json`, or the guard itself (symlinks resolved), and commands that name those files, `PI_CODING_AGENT_DIR`, or `mcp add|login|logout|remove`, are blocked with a note to use the Connectors screen.+### Switching and history races (S21)- Opening or starting another conversation while the assistant answers first asks the user ("Stop and switch" or "Cancel"). The daemon then aborts the run and waits, bounded to 10 s, for it to settle before it sends `new_session` or `switch_session` (abort-then-switch): Pi would otherwise end the run inside the new session. That stop is reported as `stopped`, never as an error.@@ -159,7 +175,7 @@ The UI shows one endless chat: no conversations list, no new conversation, and t### The panel (expanded)- 420 × 640 px, rounded 20 px, translucent (macOS vibrancy), anchored to the Dot.-- Header (one continuous chat): the rose glyph and "Gentle Dot", then Accounts, Profiles, and Hide as 18 px stroke icons with tooltips. With `features.conversations` on, the conversation title, the conversations list, and New conversation return.+- Header (one continuous chat): the rose glyph and "Gentle Dot", then Accounts, Profiles, Connectors (a plug; also `/connectors`), and Hide as 18 px stroke icons with tooltips. With `features.conversations` on, the conversation title, the conversations list, and New conversation return.- "Show earlier" at the top of the chat loads the previous page; a subtle "Earlier messages" divider marks where the chat's earlier session ends.- Body: message list with streaming Markdown and code blocks; activity rows are collapsed one-liners grouped under the assistant turn ("Read 3 files · Ran tests").- Ask cards: when the agent needs the user, an inline card with the question and buttons (select and confirm) or a text field (input and editor). The Dot turns amber until the user answers.@@ -169,7 +185,7 @@ The UI shows one endless chat: no conversations list, no new conversation, and t### Menu bar- Template icon: the hand-drawn rose glyph (`docs/brand/rose-glyph.svg`), with one variant per state: ready, working (dashed outer petals; also used while thinking), needs you (a filled badge dot), and unavailable (dimmed; starting, restarting, and error).-- Menu: Open (`⌥ Space`), New conversation, Open in browser, Restart assistant, Launch at login (toggle), Quit. In the single chat the UI ignores New conversation; hiding the item in the tray is a follow-up for `apps/desktop`.+- Menu: Open (`⌥ Space`), Open in browser, Restart assistant, Launch at login (toggle), Quit. New conversation appears after Open only with the conversations list on (`GENTLE_DOT_CONVERSATIONS=1`).### Web@@ -241,7 +257,7 @@ The Dot drags with `getCurrentWindow().startDragging()` (permission `core:window### Menu bar and shortcut-Tray menu: Open (`⌥ Space`), New conversation, Open in browser, Restart assistant, Launch at login (check item), Quit. The global shortcut `Alt+Space` (configurable as `shortcut` in `config.json`) toggles the panel. Launch at login uses `tauri-plugin-autostart`; Open in browser uses `tauri-plugin-opener` with `webUrl`.+Tray menu: Open (`⌥ Space`), New conversation (only with `GENTLE_DOT_CONVERSATIONS=1`, read like the daemon reads it), Open in browser, Restart assistant, Launch at login (check item), Quit. The global shortcut `Alt+Space` (configurable as `shortcut` in `config.json`) toggles the panel. Launch at login uses `tauri-plugin-autostart`; Open in browser uses `tauri-plugin-opener` with `webUrl`.### Daemon lifecycle@@ -257,4 +273,4 @@ On launch, the app checks `GET /health`. If the daemon does not answer, the appAll keys are optional. `workspace` is the user's preferred working folder: the engine is told about it but always runs in `<dataDir>/workspace`.-Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array), `GENTLE_DOT_CONVERSATIONS` (`1` turns the conversations list on), `GENTLE_DOT_ROTATE_BYTES` (default 20 MB), `GENTLE_DOT_ROTATE_COMPACTIONS` (default 10), `GENTLE_DOT_HISTORY_PAGE` (default 100).+Environment overrides: `GENTLE_DOT_AGENT_HOME` (default `~/.gentle-dot/agent`), `GENTLE_DOT_ENGRAM_DATA_DIR` (default: the user's Engram data folder), `GENTLE_DOT_ENGRAM` (`private` for a memory of the assistant's own), `GENTLE_DOT_ENGRAM_PORT` (private memory only, default `7438`), `GENTLE_DOT_PORT`, `GENTLE_DOT_HOST` (default `127.0.0.1`; `0.0.0.0` only inside a container), `GENTLE_DOT_DATA_DIR`, `GENTLE_DOT_WORKSPACE`, `GENTLE_DOT_UI_DIR`, `GENTLE_DOT_AGENT_BIN`, `GENTLE_DOT_AGENT_ARGS` (JSON array), `GENTLE_DOT_ALLOWED_ORIGINS` (JSON array), `GENTLE_DOT_CONVERSATIONS` (`1` turns the conversations list on), `GENTLE_DOT_ROTATE_BYTES` (default 20 MB), `GENTLE_DOT_ROTATE_COMPACTIONS` (default 10), `GENTLE_DOT_HISTORY_PAGE` (default 100), `GENTLE_DOT_MCP_CLI` (JSON array: the command line used for connector sign-in, for tests; default the bundled engine's).diff --git a/e2e/serve.ts b/e2e/serve.tsindex 99735df..3636b38 100644--- a/e2e/serve.ts+++ b/e2e/serve.ts@@ -37,6 +37,11 @@ process.env.FAKE_AGENT_COMMANDS_FILE = conversations? join(dataDir, "agent-commands.jsonl"): E2E_COMMANDS_FILE;process.env.GENTLE_DOT_DATA_DIR = dataDir;+// Connector sign-in runs a stand-in for the engine's `mcp login`, which waits for the pasted address.+process.env.GENTLE_DOT_MCP_CLI = JSON.stringify([+ process.execPath,+ fileURLToPath(new URL("../packages/daemon/test/fixtures/fake-mcp-cli.ts", import.meta.url)),+]);process.env.GENTLE_DOT_AGENT_BIN = process.execPath;process.env.GENTLE_DOT_AGENT_ARGS = JSON.stringify([fileURLToPath(new URL("../packages/daemon/test/fixtures/fake-agent.ts", import.meta.url)),diff --git a/e2e/web.spec.ts b/e2e/web.spec.tsindex 88b4cf8..138acac 100644--- a/e2e/web.spec.ts+++ b/e2e/web.spec.ts@@ -215,6 +215,79 @@ test("opens accounts with /login, offers subscriptions without Claude, and conneawait expect(page.getByRole("textbox", { name: "Message" })).toBeVisible();});+test("connects Notion from the Connectors screen, switches its mode, and removes it", async ({ page }) => {+ // The sign-in page would open in a new tab; keep its address instead.+ await page.addInitScript(() => {+ const opened: string[] = [];+ (window as unknown as { opened: string[] }).opened = opened;+ window.open = (url?: string | URL) => {+ opened.push(String(url));+ return null;+ };+ });+ await open(page);+ await page.getByRole("button", { name: "Connectors" }).click();+ const screen = page.getByRole("region", { name: "Connectors" });+ for (const name of ["Notion", "Linear", "Atlassian"]) {+ await expect(screen.getByRole("listitem", { name })).toBeVisible();+ }+ const notion = screen.getByRole("listitem", { name: "Notion" });+ await expect(notion).toContainText("It cannot send or change anything.");+ await notion.getByRole("button", { name: "Connect Notion" }).click();++ await expect(screen).toContainText("Signing in to Notion");+ await screen.getByRole("button", { name: "Open the sign-in page" }).click();+ const link = await page.evaluate(() => (window as unknown as { opened: string[] }).opened[0] ?? "");+ expect(link).toMatch(/^https:\/\/auth\.example\.com\/authorize\?/);+ await page.screenshot({ path: "/tmp/gentle-dot-t18a/connectors-signin.png" });+ // The browser could not reach this computer: paste the address it ended on.+ const redirect = new URL(new URL(link).searchParams.get("redirect_uri") ?? "");+ redirect.search = "?code=e2e-code&state=fake-state";+ await screen.getByLabel(/paste it here/).fill(redirect.href);+ await screen.getByRole("button", { name: "Continue" }).click();+ await expect(screen.getByRole("status")).toHaveText("Connected to Notion.");+ await screen.getByRole("button", { name: "Back to connectors" }).click();++ await expect(notion.getByText("Connected", { exact: true })).toBeVisible();+ await expect(notion.getByRole("radio", { name: "Read only" })).toBeChecked();+ // The choice is the daemon's: the radio follows the list it sends back.+ await notion.getByRole("radio", { name: "Read and send" }).click();+ await expect(notion.getByRole("radio", { name: "Read and send" })).toBeChecked();+ await expect(notion).toContainText("after you approve each one");+ await page.screenshot({ path: "/tmp/gentle-dot-t18a/connectors-screen.png" });+ const mcp = JSON.parse(readFileSync(join(E2E_DATA_DIR, "agent", "mcp.json"), "utf8"));+ expect(mcp).toEqual({ mcpServers: { notion: { url: "https://mcp.notion.com/mcp", exposure: "direct" } } });++ await notion.getByRole("button", { name: "Remove Notion" }).click();+ await expect(notion.getByRole("button", { name: "Connect Notion" })).toBeVisible();+ await expect(notion.getByText("Connected", { exact: true })).toHaveCount(0);+ expect(JSON.parse(readFileSync(join(E2E_DATA_DIR, "agent", "mcp.json"), "utf8"))).toEqual({+ mcpServers: {},+ });+ await screen.getByRole("button", { name: "Close connectors" }).click();++ // Typing /connectors opens the screen; it never reaches the assistant.+ const sent = await page.locator(".message-user").count();+ await say(page, "/connectors");+ await expect(screen).toBeVisible();+ await expect(page.locator(".message-user")).toHaveCount(sent);+});++test("shows a connector action as an approval card with a preview", async ({ page }) => {+ await open(page);+ await say(page, "ask:approval");+ const card = page.getByRole("region", { name: "The assistant needs your answer" });+ await expect(card).toContainText("Allow Notion to create pages?");+ await expect(card).toContainText("parent: Team notes");+ await expect(card).toContainText("title: Weekly plan");+ await expect(card.locator(".ask-message")).toHaveCSS("white-space", "pre-wrap");+ await card.screenshot({ path: "/tmp/gentle-dot-t18a/approval-card.png" });+ await page.screenshot({ path: "/tmp/gentle-dot-t18a/approval-card-panel.png" });+ await card.getByRole("button", { name: "No" }).click();+ await expect(card).toBeHidden();+ await expect(page.locator(".message-assistant").last()).toHaveText("I did not create the page");+});+test("creates a profile with /profiles, edits a role, and switches to it", async ({ page }) => {await open(page);await say(page, "/profiles");diff --git a/packages/daemon/src/bridge.ts b/packages/daemon/src/bridge.tsindex 9b30c46..f796404 100644--- a/packages/daemon/src/bridge.ts+++ b/packages/daemon/src/bridge.ts@@ -11,6 +11,7 @@ import {type ServerPayload,} from "@gentle-dot/protocol";import type { AuthManager } from "./auth.ts";+import type { ConnectorManager, ConnectorRefusal } from "./connectors.ts";import {conversationIdOf,type HistoryPage,@@ -39,6 +40,7 @@ export interface BridgeOptions {log?: (line: string) => void;auth?: AuthManager;profiles?: ProfileStore;+ connectors?: ConnectorManager;/** 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. */@@ -98,6 +100,8 @@ export class DotBridge {private queue: MessageQueue = { steering: [], followUp: [] };/** Messages on their way to the agent; the session is never rotated under them. */private sending = 0;+ /** A run settled while a message was still on its way; check for rotation once it arrived. */+ private rotationDeferred = false;private readonly features: Features;private readonly rotator: SessionRotator;private readonly liveSwitch: LiveModelSwitch;@@ -116,6 +120,7 @@ export class DotBridge {});supervisor.onEvent((event) => this.onAgentEvent(event));if (options.auth) options.auth.onCredentialsChanged = () => this.afterCredentialsChange();+ if (options.connectors) options.connectors.onChanged = (restart) => this.afterConnectorsChange(restart);this.state = this.deriveState();}@@ -138,6 +143,7 @@ export class DotBridge {return () => {this.clients.delete(client);this.options.auth?.cancelOwnedBy(client);+ this.options.connectors?.cancelOwnedBy(client);};}@@ -196,6 +202,14 @@ export class DotBridge {await this.sendProfiles(client, true);return;}+ if (/^\s*\/connectors\s*$/i.test(message.text)) {+ this.deliver(client, {+ type: "connectors",+ connectors: this.requireConnectors().list(),+ open: true,+ });+ return;+ }await this.switching;this.interrupted = false;const busy = this.supervisor.busy;@@ -208,6 +222,11 @@ export class DotBridge {);} finally {this.sending -= 1;+ // The run may have settled before the answer to this prompt was handled.+ if (this.sending === 0 && this.rotationDeferred) {+ this.rotationDeferred = false;+ if (!this.supervisor.busy) this.rotateWhenIdle();+ }}return;}@@ -281,7 +300,11 @@ export class DotBridge {return;}case "auth_reply":- if (!this.requireAuth().reply(client, message.flowId, message)) {+ if (+ this.options.connectors?.owns(message.flowId)+ ? !this.options.connectors.reply(client, message.flowId, message)+ : !this.requireAuth().reply(client, message.flowId, message)+ ) {this.deliver(client, {type: "error",code: "auth_flow_not_found",@@ -297,6 +320,16 @@ export class DotBridge {case "profiles_list":await this.sendProfiles(client);return;+ case "connectors_list":+ this.deliver(client, { type: "connectors", connectors: this.requireConnectors().list() });+ return;+ case "connector_connect":+ case "connector_signin":+ case "connector_disconnect":+ case "connector_mode":+ case "connector_remove":+ await this.connectorCommand(client, message);+ return;case "profile_save":case "profile_rename":case "profile_duplicate":@@ -410,6 +443,47 @@ export class DotBridge {this.deliver(client, { type: "auth_providers", providers, ...(open ? { open: true } : {}) });}+ private requireConnectors(): ConnectorManager {+ if (!this.options.connectors) throw new Error("connectors are not available");+ return this.options.connectors;+ }++ /** Runs one connector change; a sign-in's steps go only to the window that started it. */+ private async connectorCommand(+ client: BridgeClient,+ message: Extract<ClientMessage, { connectorId: string }>,+ ): Promise<void> {+ const connectors = this.requireConnectors();+ const emit = (payload: ServerPayload) => this.deliver(client, payload);+ let refused: ConnectorRefusal | undefined;+ switch (message.type) {+ case "connector_connect":+ refused = connectors.connect(client, message.connectorId, emit);+ break;+ case "connector_signin":+ refused = connectors.signIn(client, message.connectorId, emit);+ break;+ case "connector_disconnect":+ refused = connectors.disconnect(message.connectorId);+ break;+ case "connector_mode":+ refused = connectors.setMode(message.connectorId, message.mode);+ break;+ case "connector_remove":+ refused = await connectors.remove(message.connectorId);+ break;+ }+ if (refused) this.deliver(client, { type: "error", ...refused });+ }++ /** Every window sees the new statuses; a new mcp.json needs an agent restart, once it is idle. */+ private afterConnectorsChange(restart: boolean): void {+ this.broadcast({ type: "connectors", connectors: this.requireConnectors().list() });+ if (!restart) return;+ if (this.supervisor.busy) this.restartPending = true;+ else this.restartAgent();+ }+private requireProfiles(): ProfileStore {if (!this.options.profiles) throw new Error("profiles are not available");return this.options.profiles;@@ -621,6 +695,7 @@ export class DotBridge {this.broadcast(this.conversationsPayload());this.settleModelSwitch();if (this.restartPending) this.restartAgent();+ else if (this.sending > 0) this.rotationDeferred = true;else this.rotateWhenIdle();break;case "extension_ui_request":diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsnew file mode 100644index 0000000..e19e9bb--- /dev/null+++ b/packages/daemon/src/connectors.ts@@ -0,0 +1,575 @@+import { type ChildProcess, spawn } from "node:child_process";+import { createHash, randomUUID } from "node:crypto";+import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+import type { ConnectorInfo, ConnectorMode, ServerPayload } from "@gentle-dot/protocol";+import { type ConnectorPolicy, POLICY_ENV } from "./extensions/approval-guard.ts";++/** A service in the catalog: an official remote MCP server with OAuth sign-in. */+export interface CatalogEntry {+ id: string;+ name: string;+ url: string;+ reads: string;+ sends: string;+ /**+ * Tools that only read, by their MCP names. A tool also has to declare `readOnlyHint: true`;+ * anything else needs the user's approval, and read-only mode hides it.+ */+ readOnlyTools: readonly string[];+}++/** Official remote servers, checked against each provider's documentation on 2026-10-08. */+export const CATALOG: readonly CatalogEntry[] = [+ {+ id: "notion",+ name: "Notion",+ url: "https://mcp.notion.com/mcp",+ reads: "Search and read your pages, databases, and comments.",+ sends: "Create and edit pages and add comments, after you approve each one.",+ readOnlyTools: [+ "notion-search",+ "notion-fetch",+ "notion-get-comments",+ "notion-get-teams",+ "notion-get-users",+ "notion-query-data-sources",+ "notion-query-meeting-notes",+ ],+ },+ {+ id: "linear",+ name: "Linear",+ url: "https://mcp.linear.app/mcp",+ reads: "Find and read issues, projects, cycles, and comments.",+ sends: "Create and update issues, projects, and comments, after you approve each one.",+ readOnlyTools: [+ "list_issues",+ "get_issue",+ "list_comments",+ "list_projects",+ "get_project",+ "list_teams",+ "get_team",+ "list_users",+ "get_user",+ "list_issue_statuses",+ "get_issue_status",+ "list_issue_labels",+ "list_cycles",+ "list_documents",+ "get_document",+ "search_documentation",+ ],+ },+ {+ id: "atlassian",+ name: "Atlassian",+ url: "https://mcp.atlassian.com/v2/mcp",+ reads: "Search and read Jira issues and Confluence pages.",+ sends: "Create and edit Jira issues and Confluence pages, and comment, after you approve each one.",+ readOnlyTools: [+ "atlassianUserInfo",+ "getAccessibleAtlassianResources",+ "search",+ "fetch",+ "searchJiraIssuesUsingJql",+ "getJiraIssue",+ "listJiraIssueComments",+ "listJiraProjects",+ "lookupJiraAccountId",+ "searchConfluence",+ "getConfluenceContent",+ "listConfluenceContent",+ "listConfluenceSpaces",+ "getConfluenceSpace",+ "listConfluenceComments",+ ],+ },+];++const catalogEntry = (id: string) => CATALOG.find((entry) => entry.id === id);++export interface ConnectorsState {+ connectors: Record<string, { enabled: boolean; mode: ConnectorMode }>;+}++/**+ * The engine's `mcp.json` for the added connectors. The assistant turns codemode off, so every+ * server is `direct`. Read only hides every tool (`*`) except the curated ones (exact names win+ * over patterns in the engine), so a tool the catalog does not know stays hidden.+ */+export function renderMcpJson(state: ConnectorsState): string {+ const servers: Record<string, unknown> = {};+ for (const entry of CATALOG) {+ const saved = state.connectors[entry.id];+ if (!saved) continue;+ servers[entry.id] = {+ url: entry.url,+ exposure: "direct",+ ...(saved.mode === "read_only"+ ? {+ toolExposure: {+ "*": "hidden",+ ...Object.fromEntries(entry.readOnlyTools.map((tool) => [tool, "direct"])),+ },+ }+ : {}),+ ...(saved.enabled ? {} : { enabled: false }),+ };+ }+ return `${JSON.stringify({ mcpServers: servers }, null, 2)}\n`;+}++const sha256 = (text: string) => createHash("sha256").update(text).digest("hex");++function writePrivate(path: string, text: string): void {+ const temp = `${path}.${process.pid}.tmp`;+ writeFileSync(temp, text, { mode: 0o600 });+ renameSync(temp, path);+}++export interface ConnectorStoreOptions {+ dataDir: string;+ /** The engine's home, which holds `mcp.json` and `mcp-auth.json`. */+ agentHome: string;+ /** The approval guard's own file, protected like the connector files. */+ guardPath?: string;+ log?: (line: string) => void;+}++/**+ * The daemon's record of the connectors (`<data>/connectors.json`) and the only writer of the+ * engine's `mcp.json`, which it renders from that record. The record keeps the hash of the+ * approved `mcp.json`, so a file changed by anything else is put back before the engine starts.+ */+export class ConnectorStore {+ readonly file: string;+ readonly mcpFile: string;+ readonly authFile: string;+ private readonly options: ConnectorStoreOptions;++ constructor(options: ConnectorStoreOptions) {+ this.options = options;+ this.file = join(options.dataDir, "connectors.json");+ this.mcpFile = join(options.agentHome, "mcp.json");+ this.authFile = join(options.agentHome, "mcp-auth.json");+ }++ get agentHome(): string {+ return this.options.agentHome;+ }++ state(): ConnectorsState {+ return { connectors: this.read().connectors };+ }++ /** Changes the record, then writes both files (each atomically, mode 0600). */+ update(change: (state: ConnectorsState) => void): void {+ const state = this.state();+ change(state);+ const rendered = renderMcpJson(state);+ mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });+ writePrivate(+ this.file,+ `${JSON.stringify({ version: 1, connectors: state.connectors, hash: sha256(rendered) }, null, 2)}\n`,+ );+ writePrivate(this.mcpFile, rendered);+ }++ /** Puts the approved `mcp.json` back when it changed; true when it had to. */+ ensureMcpJson(): boolean {+ const saved = this.read();+ const current = existsSync(this.mcpFile) ? readFileSync(this.mcpFile, "utf8") : undefined;+ const nothingAdded = saved.hash === undefined && Object.keys(saved.connectors).length === 0;+ if (current === undefined && nothingAdded) return false;+ if (current !== undefined && saved.hash !== undefined && sha256(current) === saved.hash) return false;+ const rendered = renderMcpJson({ connectors: saved.connectors });+ mkdirSync(this.options.agentHome, { recursive: true, mode: 0o700 });+ writePrivate(this.mcpFile, rendered);+ this.options.log?.(+ "mcp.json was changed outside the Connectors screen; restored the approved connectors",+ );+ return true;+ }++ /** What the approval guard enforces: the turned-on connectors and the files only the daemon writes. */+ policy(): ConnectorPolicy {+ const connectors: NonNullable<ConnectorPolicy["connectors"]> = {};+ for (const [id, saved] of Object.entries(this.state().connectors)) {+ const entry = catalogEntry(id);+ if (entry && saved.enabled)+ connectors[id] = { name: entry.name, mode: saved.mode, readOnlyTools: [...entry.readOnlyTools] };+ }+ return {+ connectors,+ protectedPaths: [+ this.mcpFile,+ this.authFile,+ this.file,+ ...(this.options.guardPath ? [this.options.guardPath] : []),+ ],+ };+ }++ /**+ * True when the engine stored tokens for the connector (key `mcp__<id>|<url>`). Token values+ * are dropped while parsing, so they are never kept or passed on.+ */+ isSignedIn(id: string): boolean {+ const entry = catalogEntry(id);+ if (!entry || !existsSync(this.authFile)) return false;+ try {+ const states = JSON.parse(readFileSync(this.authFile, "utf8"), (key, value) =>+ key === "tokens" && typeof value === "object" && value !== null ? {} : value,+ ) as Record<string, { tokens?: unknown } | undefined>;+ return typeof states[`mcp__${id}|${new URL(entry.url).href}`]?.tokens === "object";+ } catch {+ return false;+ }+ }++ private read(): { connectors: ConnectorsState["connectors"]; hash?: string } {+ try {+ const saved = JSON.parse(readFileSync(this.file, "utf8")) as {+ connectors?: Record<string, { enabled?: unknown; mode?: unknown }>;+ hash?: unknown;+ };+ const connectors: ConnectorsState["connectors"] = {};+ for (const [id, value] of Object.entries(saved.connectors ?? {})) {+ if (!catalogEntry(id)) continue;+ connectors[id] = {+ enabled: value?.enabled === true,+ mode: value?.mode === "read_write" ? "read_write" : "read_only",+ };+ }+ return { connectors, ...(typeof saved.hash === "string" ? { hash: saved.hash } : {}) };+ } catch {+ return { connectors: {} };+ }+ }+}++/** How to run the engine's command line: `command ...args mcp <subcommand> <server>`. */+export interface McpCli {+ command: string;+ args: string[];+}++/** The command line of the engine bundled with the daemon (`pi-coding-agent`). */+export function bundledMcpCli(): McpCli {+ const require = createRequire(import.meta.url);+ for (const dir of require.resolve.paths("@earendil-works/pi-coding-agent") ?? []) {+ const cli = join(dir, "@earendil-works", "pi-coding-agent", "dist", "bundle", "cli.js");+ if (existsSync(cli)) return { command: process.execPath, args: [cli] };+ }+ throw new Error("The bundled assistant engine is missing. Run `pnpm install`.");+}++/** The approval guard the daemon loads into the engine. */+export const APPROVAL_GUARD = fileURLToPath(new URL("./extensions/approval-guard.ts", import.meta.url));++/** Why a connector action did not start; `message` is safe to show. */+export type ConnectorRefusal = {+ code: "connector_busy" | "unknown_connector" | "connector_not_added";+ message: string;+};++const REFUSALS = {+ busy: { code: "connector_busy", message: "Another sign-in is in progress. Finish or cancel it first." },+ unknown: { code: "unknown_connector", message: "That connector is not available." },+ notAdded: { code: "connector_not_added", message: "Connect that service first." },+} as const satisfies Record<string, ConnectorRefusal>;++type Emit = (payload: ServerPayload) => void;++interface Flow {+ id: string;+ connectorId: string;+ owner: object;+ emit: Emit;+ child: ChildProcess;+ /** From the authorization URL: where the browser returns, and the sign-in's `state`. */+ redirect?: { url: URL; state: string | null };+ cancelled: boolean;+ /** What the command printed so far: stdout until the link appears, the tail of stderr for the log. */+ printed: string | undefined;+ output: string;+}++const PASTE_PROMPT =+ "If the browser shows an error page after you approve, copy the full address from its address bar and paste it here.";++export interface ConnectorManagerOptions {+ store: ConnectorStore;+ cli: McpCli;+ /** The engine's environment (its own HOME, XDG folders, and memory settings). */+ env: NodeJS.ProcessEnv;+ cwd: string;+ log?: (line: string) => void;+}++/**+ * Connects, signs in, changes, and removes connectors. Sign-in runs the engine's own+ * `mcp login <server>` as a separate process (one at a time; its loopback callback port is+ * shared), relays the authorization URL, and can finish with an address the user pastes when+ * the browser could not reach this computer. Nothing typed or printed is logged.+ */+export class ConnectorManager {+ /** `restart`: the engine must restart (when idle) to read the new `mcp.json`. */+ onChanged: (restart: boolean) => void = () => {};+ private flow: Flow | undefined;+ private readonly failed = new Set<string>();+ private readonly options: ConnectorManagerOptions;++ constructor(options: ConnectorManagerOptions) {+ this.options = options;+ }++ list(): ConnectorInfo[] {+ const { connectors } = this.options.store.state();+ return CATALOG.map((entry) => {+ const saved = connectors[entry.id];+ const status = !saved?.enabled+ ? "off"+ : this.failed.has(entry.id)+ ? "error"+ : this.options.store.isSignedIn(entry.id)+ ? "connected"+ : "needs_signin";+ return {+ id: entry.id,+ name: entry.name,+ reads: entry.reads,+ sends: entry.sends,+ added: saved !== undefined,+ enabled: saved?.enabled === true,+ mode: saved?.mode ?? "read_only",+ status,+ };+ });+ }++ /** Adds or turns on a connector, then signs in when it has no sign-in yet. */+ connect(owner: object, id: string, emit: Emit): ConnectorRefusal | undefined {+ if (!catalogEntry(id)) return REFUSALS.unknown;+ if (this.flow) return REFUSALS.busy;+ this.options.store.update((state) => {+ state.connectors[id] = { enabled: true, mode: state.connectors[id]?.mode ?? "read_only" };+ });+ this.onChanged(true);+ if (!this.options.store.isSignedIn(id)) this.startLogin(owner, id, emit);+ // Already signed in: the window that asked is told it is done.+ else emit({ type: "auth_done", flowId: `connector-${randomUUID()}`, providerId: id, ok: true });+ return undefined;+ }++ signIn(owner: object, id: string, emit: Emit): ConnectorRefusal | undefined {+ if (!catalogEntry(id)) return REFUSALS.unknown;+ if (this.flow) return REFUSALS.busy;+ if (!this.options.store.state().connectors[id]) return REFUSALS.notAdded;+ this.startLogin(owner, id, emit);+ return undefined;+ }++ /** Answers the flow `owner` started: a pasted address, or a cancellation. */+ reply(owner: object, flowId: string, answer: { value?: string; cancelled?: boolean }): boolean {+ const flow = this.flow;+ if (!flow || flow.id !== flowId || flow.owner !== owner) return false;+ if (answer.cancelled) {+ this.cancel(flow);+ return true;+ }+ if (answer.value === undefined) return false;+ void this.finishWithPastedAddress(flow, answer.value);+ return true;+ }++ owns(flowId: string): boolean {+ return flowId.startsWith("connector-");+ }++ /** A window that goes away takes its sign-in with it. */+ cancelOwnedBy(owner: object): void {+ if (this.flow?.owner === owner) this.cancel(this.flow);+ }++ cancelAll(): void {+ if (this.flow) this.cancel(this.flow);+ }++ /** Turns a connector off; its sign-in is kept for when it is turned on again. */+ disconnect(id: string): ConnectorRefusal | undefined {+ return this.change(id, (saved) => ({ ...saved, enabled: false }));+ }++ setMode(id: string, mode: ConnectorMode): ConnectorRefusal | undefined {+ return this.change(id, (saved) => ({ ...saved, mode }));+ }++ /** Signs out (`mcp logout`, which needs the server still configured), then forgets the connector. */+ async remove(id: string): Promise<ConnectorRefusal | undefined> {+ if (!catalogEntry(id)) return REFUSALS.unknown;+ if (!this.options.store.state().connectors[id]) return REFUSALS.notAdded;+ if (this.flow?.connectorId === id) this.cancel(this.flow);+ const code = await new Promise<number | null>((done) => {+ const child = this.run("logout", id);+ child.on("error", () => done(-1));+ child.on("close", (exit) => done(exit));+ });+ if (code !== 0) this.log(`sign-out of connector ${id} failed (exit ${code})`);+ this.failed.delete(id);+ this.options.store.update((state) => {+ delete state.connectors[id];+ });+ this.onChanged(true);+ return undefined;+ }++ private change(+ id: string,+ update: (saved: ConnectorsState["connectors"][string]) => ConnectorsState["connectors"][string],+ ): ConnectorRefusal | undefined {+ if (!catalogEntry(id)) return REFUSALS.unknown;+ const saved = this.options.store.state().connectors[id];+ if (!saved) return REFUSALS.notAdded;+ this.options.store.update((state) => {+ state.connectors[id] = update(saved);+ });+ this.onChanged(true);+ return undefined;+ }++ private run(subcommand: "login" | "logout", id: string): ChildProcess {+ const { cli, env, cwd } = this.options;+ return spawn(cli.command, [...cli.args, "mcp", subcommand, id], {+ cwd,+ env: { ...env, PI_CODING_AGENT_DIR: this.options.store.agentHome },+ stdio: ["ignore", "pipe", "pipe"],+ });+ }++ private startLogin(owner: object, connectorId: string, emit: Emit): void {+ const child = this.run("login", connectorId);+ const flow: Flow = {+ id: `connector-${randomUUID()}`,+ connectorId,+ owner,+ emit,+ child,+ cancelled: false,+ printed: "",+ output: "",+ };+ this.flow = flow;+ this.failed.delete(connectorId);+ child.stdout?.on("data", (chunk: Buffer) => this.onOutput(flow, chunk.toString("utf8")));+ child.stderr?.on("data", (chunk: Buffer) => {+ flow.output = `${flow.output}${chunk.toString("utf8")}`.slice(-2000);+ });+ child.on("error", (error) => this.log(`connector sign-in could not start: ${error.message}`));+ child.on("close", (code) => this.onExit(flow, code));+ }++ private onOutput(flow: Flow, text: string): void {+ if (flow.printed === undefined) return;+ flow.printed = `${flow.printed}${text}`.slice(-8000);+ // The link ends with its line; a chunk may stop in the middle of it.+ const url = flow.printed.match(/https?:\/\/\S+(?=\s)/)?.[0];+ if (!url || !URL.canParse(url)) return;+ flow.printed = undefined;+ const authorization = new URL(url);+ const redirect = authorization.searchParams.get("redirect_uri");+ if (redirect && URL.canParse(redirect))+ flow.redirect = { url: new URL(redirect), state: authorization.searchParams.get("state") };+ const name = catalogEntry(flow.connectorId)?.name ?? flow.connectorId;+ flow.emit({+ type: "auth_event",+ flowId: flow.id,+ event: {+ kind: "auth_url",+ url,+ instructions: `Open the ${name} page and approve access. You can come back here when it says you are done.`,+ },+ });+ this.askForAddress(flow);+ }++ private askForAddress(flow: Flow, retry = false): void {+ flow.emit({+ type: "auth_prompt",+ prompt: {+ flowId: flow.id,+ kind: "manual_code",+ message: retry ? `That address is not from this sign-in. ${PASTE_PROMPT}` : PASTE_PROMPT,+ },+ });+ }++ /**+ * The browser could not reach this computer's sign-in page (for example, the assistant runs+ * elsewhere): the pasted address is that page's address, so open it here. Only the exact+ * loopback address of this sign-in, with its `state`, is accepted.+ */+ private async finishWithPastedAddress(flow: Flow, pasted: string): Promise<void> {+ const expected = flow.redirect;+ const url = URL.canParse(pasted.trim()) ? new URL(pasted.trim()) : undefined;+ const loopback = url && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);+ if (+ !expected ||+ !url ||+ !loopback ||+ url.protocol !== "http:" ||+ url.origin !== expected.url.origin ||+ url.pathname !== expected.url.pathname ||+ url.searchParams.get("state") !== expected.state+ ) {+ this.askForAddress(flow, true);+ return;+ }+ if (url.hostname === "localhost") url.hostname = "127.0.0.1";+ try {+ await fetch(url, { signal: AbortSignal.timeout(10_000) });+ } catch {+ if (this.flow === flow) this.askForAddress(flow, true);+ }+ }++ private cancel(flow: Flow): void {+ flow.cancelled = true;+ flow.child.kill("SIGTERM");+ }++ private onExit(flow: Flow, code: number | null): void {+ if (this.flow === flow) this.flow = undefined;+ const done = { type: "auth_done", flowId: flow.id, providerId: flow.connectorId } as const;+ if (code === 0 && !flow.cancelled) {+ this.log(`signed in to connector ${flow.connectorId}`);+ flow.emit({ ...done, ok: true });+ } else if (flow.cancelled) {+ flow.emit({ ...done, ok: false, message: "Sign-in cancelled." });+ } else {+ this.failed.add(flow.connectorId);+ const detail =+ flow.output+ .trim()+ .split("\n")+ .pop()+ ?.replace(/https?:\/\/\S+/g, "[address]") ?? "";+ this.log(`sign-in to connector ${flow.connectorId} failed (exit ${code}): ${detail.slice(0, 200)}`);+ flow.emit({ ...done, ok: false, message: "Sign-in did not finish. Please try again." });+ }+ this.onChanged(false);+ }++ private log(line: string): void {+ this.options.log?.(line);+ }+}++/** The guard's policy for the engine's environment; the engine cannot change its own environment. */+export function policyEnv(store: ConnectorStore): NodeJS.ProcessEnv {+ return { [POLICY_ENV]: JSON.stringify(store.policy()) };+}diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex 6fac896..e5a3993 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -7,6 +7,14 @@ import { type ClientMessage, CloseCode, PROTOCOL_VERSION, parseClientMessage } fimport { type WebSocket, WebSocketServer } from "ws";import { AuthManager, type AuthRuntime, createModelAuthRuntime, resolveAgentHome } from "./auth.ts";import { type BridgeClient, DotBridge } from "./bridge.ts";+import {+ APPROVAL_GUARD,+ bundledMcpCli,+ ConnectorManager,+ ConnectorStore,+ type McpCli,+ policyEnv,+} from "./connectors.ts";import { ensureMemoryProject, ensurePrivateDir, isolatedAgentEnv } from "./isolation.ts";import { defaultImportPath, ProfileStore } from "./profiles.ts";import { type RotationLimits, rotationLimits } from "./rotation.ts";@@ -33,6 +41,8 @@ export interface DaemonOptions {profilesImportPath?: string;/** Creates the sign-in runtime; defaults to Pi's ModelRuntime on the agent home. */authRuntime?: () => Promise<AuthRuntime>;+ /** The engine's command line for connector sign-in; default `GENTLE_DOT_MCP_CLI` (JSON array) or the bundled one. */+ connectorCli?: McpCli;/** Origins allowed to open the WebSocket, besides the daemon's own and the desktop app's. */allowedOrigins?: string[];backoffMs?: number[];@@ -111,19 +121,41 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {agentEnv = isolatedAgentEnv(agentEnv, options.dataDir);agentEnv.GENTLE_PI_CONFIG_HOME = join(options.dataDir, "gentle-ai");}+ const agentHome = options.agentHome ?? resolveAgentHome(process.env, options.dataDir);+ const connectorStore = new ConnectorStore({+ dataDir: options.dataDir,+ agentHome,+ guardPath: APPROVAL_GUARD,+ log,+ });+ // The assistant's own engine loads the approval guard for connector actions.+ const guardArgs = options.agentHome ? ["-e", APPROVAL_GUARD] : [];const supervisor = new AgentSupervisor({command: options.agentCommand,args: [...(options.agentArgs ?? []), ...homeArgs],- extraArgs: [...identityArgs(options.dataDir), ...folderArgs, ...(options.agentExtraArgs ?? [])],+ extraArgs: [+ ...identityArgs(options.dataDir),+ ...folderArgs,+ ...guardArgs,+ ...(options.agentExtraArgs ?? []),+ ],cwd: options.workspace,dataDir: options.dataDir,env: agentEnv,+ // mcp.json is read when a session starts: put back anything not approved, and hand the guard its policy.+ prepareSpawn: () => {+ try {+ connectorStore.ensureMcpJson();+ } catch (error) {+ log(`could not check mcp.json: ${(error as Error).message}`);+ }+ return policyEnv(connectorStore);+ },// The first start in a new home installs the engine's companion packages....(options.agentHome ? { startTimeoutMs: 180_000 } : {}),...(options.backoffMs ? { backoffMs: options.backoffMs } : {}),log: (line) => log(`[agent] ${line}`),});- const agentHome = options.agentHome ?? resolveAgentHome(process.env, options.dataDir);const auth = new AuthManager({runtime: options.authRuntime ?? (() => createModelAuthRuntime(agentHome, options.workspace)),log,@@ -133,12 +165,20 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {agentHome,importPath: options.profilesImportPath ?? defaultImportPath(process.env),});+ const connectors = new ConnectorManager({+ store: connectorStore,+ cli: options.connectorCli ?? mcpCliFromEnv(process.env) ?? bundledMcpCli(),+ env: { ...agentEnv },+ cwd: options.workspace,+ log,+ });const historyPage = options.historyPage ?? Number(process.env.GENTLE_DOT_HISTORY_PAGE);const bridge = new DotBridge(supervisor, {dataDir: options.dataDir,log,auth,profiles,+ connectors,features: { conversations: options.conversations ?? process.env.GENTLE_DOT_CONVERSATIONS === "1" },rotation: options.rotation ?? rotationLimits(process.env),...(Number.isInteger(historyPage) && historyPage > 0 ? { historyPage } : {}),@@ -181,6 +221,12 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {};}+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[];+ return command ? { command, args } : undefined;+}+function allowedOrigins(port: number, options: DaemonOptions): Set<string> {return new Set([`http://127.0.0.1:${port}`,diff --git a/packages/daemon/src/extensions/approval-guard.ts b/packages/daemon/src/extensions/approval-guard.tsnew file mode 100644index 0000000..487fe4c--- /dev/null+++ b/packages/daemon/src/extensions/approval-guard.ts@@ -0,0 +1,224 @@+/**+ * Approval guard, loaded into the engine with `-e` (docs/design.md §3).+ *+ * Connector tools (`mcp__<server>__<tool>`) run without asking only when they are read-only:+ * the server marks them `readOnlyHint: true` AND they are on the connector's curated list.+ * Anything else asks the user through a confirm card with a preview, and is blocked when the+ * user declines, when nobody can answer, or when the connector is set to read only. Calls made+ * by other tools (nested calls) go through the same hook.+ *+ * The policy (approved connectors, modes, curated lists, protected files) comes from the+ * daemon in this process's environment, which the assistant cannot change. Without a valid+ * policy nothing counts as read-only, so every connector call asks.+ *+ * Connectors are the user's to change: writes, edits, and commands that touch the connector+ * files or run `mcp add/login/logout/remove` are blocked with a note to use the Connectors screen.+ * This file has no dependencies besides Node, so the engine loads it as is.+ */+import { realpathSync } from "node:fs";+import { basename, dirname, isAbsolute, join, resolve } from "node:path";+import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";++export const POLICY_ENV = "GENTLE_DOT_CONNECTOR_POLICY";++export type ConnectorMode = "read_only" | "read_write";++export interface ConnectorPolicy {+ /** Approved connectors by server name; undefined when the policy is missing or invalid. */+ connectors?: Record<string, { name: string; mode: ConnectorMode; readOnlyTools: string[] }>;+ /** Files only the daemon may change. */+ protectedPaths: string[];+}++export type GuardDecision =+ | { action: "pass" }+ | { action: "ask"; title: string; message: string }+ | { action: "block"; reason: string };++export interface GuardCall {+ toolName: string;+ input: Record<string, unknown>;+ /** The tool's `readOnlyHint` annotation, as the server declared it. */+ readOnlyHint?: unknown;+ /** The working folder relative paths resolve against. */+ cwd: string;+}++const USE_CONNECTORS_SCREEN =+ "Connectors are managed by the user in the Connectors screen. Ask the user to make this change there.";+const DECLINED = "The user did not allow this action. Do not try it again unless the user asks.";+const NO_UI = "This action needs the user's approval, and no one can approve it right now.";+const CONNECTOR_COMMAND = /\bmcp\s+(?:add|login|logout|remove)\b/;+/** Arguments that say where an action goes and what it says, shown first in the preview. */+const KEY_FIELDS = [+ /^(to|cc|bcc|recipients?|channel|chat|parent|page|database|space|project|team|issue|title|subject|name)/i,+ /^(body|text|content|message|comment|description|markdown)/i,+];+const MAX_FIELDS = 6;+const MAX_VALUE = 160;++/** Like the engine's tool names: everything but letters, digits, and `_` becomes `_`. */+const toolId = (server: string, tool: string) => `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_]/g, "_");++/** Read-only only when the server declares it AND the curated list names it (fail closed). */+export function isReadOnlyCall(+ server: string,+ toolName: string,+ readOnlyHint: unknown,+ readOnlyTools: readonly string[],+): boolean {+ return readOnlyHint === true && readOnlyTools.some((tool) => toolId(server, tool) === toolName);+}++/** The policy from the daemon, or undefined when it is missing or malformed. */+export function parsePolicy(raw: string | undefined): ConnectorPolicy | undefined {+ if (!raw) return undefined;+ let value: unknown;+ try {+ value = JSON.parse(raw);+ } catch {+ return undefined;+ }+ const policy = value as Partial<ConnectorPolicy>;+ if (typeof policy !== "object" || policy === null) return undefined;+ if (!Array.isArray(policy.protectedPaths) || !policy.protectedPaths.every((p) => typeof p === "string"))+ return undefined;+ const connectors = policy.connectors;+ if (typeof connectors !== "object" || connectors === null || Array.isArray(connectors)) return undefined;+ for (const entry of Object.values(connectors)) {+ const valid =+ typeof entry === "object" &&+ entry !== null &&+ typeof entry.name === "string" &&+ (entry.mode === "read_only" || entry.mode === "read_write") &&+ Array.isArray(entry.readOnlyTools) &&+ entry.readOnlyTools.every((tool) => typeof tool === "string");+ if (!valid) return undefined;+ }+ return { connectors, protectedPaths: policy.protectedPaths };+}++export function decide(call: GuardCall, policy: ConnectorPolicy): GuardDecision {+ const { toolName, input } = call;+ if (toolName === "write" || toolName === "edit") {+ const path = input.path ?? input.file_path;+ if (typeof path === "string" && isProtected(resolvePath(path, call.cwd), policy.protectedPaths))+ return { action: "block", reason: USE_CONNECTORS_SCREEN };+ return { action: "pass" };+ }+ if (toolName === "bash") {+ const command = typeof input.command === "string" ? input.command : "";+ const touches =+ CONNECTOR_COMMAND.test(command) ||+ command.includes("PI_CODING_AGENT_DIR") ||+ policy.protectedPaths.flatMap(spellings).some((path) => command.includes(path));+ return touches ? { action: "block", reason: USE_CONNECTORS_SCREEN } : { action: "pass" };+ }+ if (!toolName.startsWith("mcp__")) return { action: "pass" };++ const approved = policy.connectors;+ const server = approved+ ? Object.keys(approved).find((id) => toolName.startsWith(toolId(id, "")))+ : /^mcp__(.+?)__/.exec(toolName)?.[1];+ if (approved && !server)+ return {+ action: "block",+ reason: "This connector is not approved. Ask the user to add it from the Connectors screen.",+ };+ const connector = server && approved ? approved[server] : undefined;+ if (connector && isReadOnlyCall(server ?? "", toolName, call.readOnlyHint, connector.readOnlyTools))+ return { action: "pass" };+ const name = connector?.name ?? server ?? "a connector";+ if (connector?.mode === "read_only")+ return {+ action: "block",+ reason: `${name} is set to read only, so this action was not run. If the user wants it, ask them to switch ${name} to "Read and send" in Connectors.`,+ };+ const action = describeAction(toolName, server ?? "");+ return {+ action: "ask",+ title: `Allow ${name} to ${action}?`,+ message: [`The assistant wants to ${action} in ${name}.`, "", ...previewLines(input)]+ .join("\n")+ .trimEnd(),+ };+}++/** `mcp__notion__notion_create_pages` -> "create pages". */+function describeAction(toolName: string, server: string): string {+ let action = toolName.slice(toolId(server, "").length);+ if (action.startsWith(`${server}_`)) action = action.slice(server.length + 1);+ const words = action.split("_").filter(Boolean).join(" ");+ return words ? words.replace(/([a-z])([A-Z])/g, "$1 $2").toLowerCase() : "use a tool";+}++function previewLines(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 keys = Object.keys(input).sort((a, b) => rank(a) - rank(b));+ const lines = keys.slice(0, MAX_FIELDS).map((key) => `${key}: ${shorten(input[key])}`);+ if (keys.length > MAX_FIELDS) lines.push(`…and ${keys.length - MAX_FIELDS} more`);+ return lines;+}++function shorten(value: unknown): string {+ const text = typeof value === "string" ? value : (JSON.stringify(value) ?? String(value));+ const short = text.length > MAX_VALUE ? `${text.slice(0, MAX_VALUE)}…` : text;+ // Lines inside one value are indented, so they do not read as fields of their own.+ return short.replace(/\n/g, "\n ");+}++function resolvePath(path: string, cwd: string): string {+ const home = process.env.HOME;+ const expanded = home && (path === "~" || path.startsWith("~/")) ? `${home}${path.slice(1)}` : path;+ return isAbsolute(expanded) ? resolve(expanded) : resolve(cwd, expanded);+}++/** A path as written and with symlinks resolved (`/var` is `/private/var` on macOS), for a missing file too. */+function spellings(path: string): string[] {+ const absolute = resolve(path);+ let real = absolute;+ try {+ real = realpathSync(absolute);+ } catch {+ try {+ real = join(realpathSync(dirname(absolute)), basename(absolute));+ } catch {}+ }+ return real === absolute ? [absolute] : [absolute, real];+}++function isProtected(path: string, protectedPaths: string[]): boolean {+ // macOS and Windows folders usually ignore case.+ const candidates = spellings(path).map((p) => p.toLowerCase());+ return protectedPaths.some((p) => spellings(p).some((s) => candidates.includes(s.toLowerCase())));+}++export default function approvalGuard(pi: ExtensionAPI): void {+ const parsed = parsePolicy(process.env[POLICY_ENV]);+ const agentDir = process.env.PI_CODING_AGENT_DIR;+ const fallback = agentDir ? [resolve(agentDir, "mcp.json"), resolve(agentDir, "mcp-auth.json")] : [];+ const policy: ConnectorPolicy = parsed ?? { protectedPaths: fallback };++ pi.on("tool_call", async (event, ctx) => {+ const annotations = event.toolName.startsWith("mcp__")+ ? pi.getAllTools().find((tool) => tool.name === event.toolName)?.annotations+ : undefined;+ const decision = decide(+ {+ toolName: event.toolName,+ input: event.input as Record<string, unknown>,+ readOnlyHint: annotations?.readOnlyHint,+ cwd: ctx.cwd,+ },+ policy,+ );+ if (decision.action === "pass") return undefined;+ if (decision.action === "block") return { block: true, reason: decision.reason };+ if (!ctx.hasUI) return { block: true, reason: NO_UI };+ const allowed = await ctx.ui.confirm(decision.title, decision.message);+ return allowed ? undefined : { block: true, reason: DECLINED };+ });+}diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.tsindex c80b7f7..d708446 100644--- a/packages/daemon/src/supervisor.ts+++ b/packages/daemon/src/supervisor.ts@@ -33,6 +33,8 @@ export interface SupervisorOptions {/** Directory for `sessions/` and `state.json` (the open session and the chains of rotated ones). */dataDir: string;env?: NodeJS.ProcessEnv;+ /** Runs before every spawn (first start, restart, respawn); returns variables added to `env`. */+ prepareSpawn?: () => NodeJS.ProcessEnv;/** Respawn delays; the last value repeats. Default 1s, 2s, 4s, 8s, 16s, 30s. */backoffMs?: number[];/** Uptime after which the backoff starts over. Default 30s. */@@ -201,10 +203,10 @@ export class AgentSupervisor {}private spawnChild(): ChildProcess {- const { command, args = [], extraArgs = [], cwd, env } = this.options;+ const { command, args = [], extraArgs = [], cwd, env, prepareSpawn } = this.options;const child = spawn(command, [...args, "--mode", "rpc", "--session-dir", this.sessionDir, ...extraArgs], {cwd,- env: env ?? process.env,+ env: { ...(env ?? process.env), ...prepareSpawn?.() },stdio: ["pipe", "pipe", "pipe"],});this.child = child;diff --git a/packages/daemon/test/approval-guard-engine.test.ts b/packages/daemon/test/approval-guard-engine.test.tsnew file mode 100644index 0000000..ee5c4b0--- /dev/null+++ b/packages/daemon/test/approval-guard-engine.test.ts@@ -0,0 +1,192 @@+// The approval guard inside the real bundled engine (pi-coding-agent's own command line), with a+// stand-in model (an OpenAI-compatible server on 127.0.0.1) and a stand-in MCP server over stdio.+// No account, network, or Gentle Shell setup is needed.+import { type ChildProcess, spawn } from "node:child_process";+import { existsSync, mkdirSync, readFileSync, writeFileSync } 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 { afterEach, describe, expect, it } from "vitest";+import { APPROVAL_GUARD, bundledMcpCli } from "../src/connectors.ts";+import { POLICY_ENV } from "../src/extensions/approval-guard.ts";+import { encodeRecord, JsonlDecoder } from "../src/jsonl.ts";+import { tempDir, waitFor } from "./helpers.ts";++const FAKE_SERVER = fileURLToPath(new URL("./fixtures/fake-mcp-server.ts", import.meta.url));++type Rec = Record<string, unknown>;+const cleanups: (() => void)[] = [];+afterEach(() => {+ for (const cleanup of cleanups.splice(0)) cleanup();+});++/** Answers the first request with the given tool calls once the MCP tools are offered, then with text. */+function fakeModel(calls: { name: string; args: Rec }[]): Promise<Server> {+ let called = false;+ const server = createServer((req, res) => {+ let body = "";+ req.on("data", (chunk: Buffer) => {+ body += chunk.toString("utf8");+ });+ req.on("end", () => {+ const tools = ((JSON.parse(body) as { tools?: { function?: { name?: string } }[] }).tools ?? []).map(+ (tool) => tool.function?.name,+ );+ res.writeHead(200, { "Content-Type": "text/event-stream" });+ const chunk = (delta: Rec, finish: string | null) =>+ res.write(+ `data: ${JSON.stringify({ id: "c", object: "chat.completion.chunk", created: 0, model: "fake-model", choices: [{ index: 0, delta, finish_reason: finish }] })}\n\n`,+ );+ if (!called && calls.every((call) => tools.includes(call.name))) {+ called = true;+ chunk(+ {+ role: "assistant",+ tool_calls: calls.map((call, index) => ({+ index,+ id: `call_${index}`,+ type: "function",+ function: { name: call.name, arguments: JSON.stringify(call.args) },+ })),+ },+ null,+ );+ chunk({}, "tool_calls");+ } else {+ chunk({ role: "assistant", content: called ? "done" : `missing tools: ${tools.join(",")}` }, null);+ chunk({}, "stop");+ }+ res.end("data: [DONE]\n\n");+ });+ });+ return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server)));+}++function startEngine(port: number) {+ const dir = tempDir();+ const agentDir = join(dir, "agent");+ const workspace = join(dir, "workspace");+ mkdirSync(agentDir, { recursive: true });+ mkdirSync(workspace, { recursive: true });+ const callsFile = join(dir, "server-calls.jsonl");+ writeFileSync(+ join(agentDir, "models.json"),+ JSON.stringify({+ providers: {+ fakeprov: {+ baseUrl: `http://127.0.0.1:${port}/v1`,+ api: "openai-completions",+ apiKey: "not-a-key",+ models: [{ id: "fake-model" }],+ },+ },+ }),+ );+ const mcpFile = join(agentDir, "mcp.json");+ writeFileSync(+ mcpFile,+ JSON.stringify({+ mcpServers: { fake: { command: process.execPath, args: [FAKE_SERVER], exposure: "direct" } },+ }),+ );+ const policy = {+ connectors: { fake: { name: "Fake Chat", mode: "read_write", readOnlyTools: ["list_messages"] } },+ protectedPaths: [mcpFile, join(agentDir, "mcp-auth.json")],+ };+ const cli = bundledMcpCli();+ const child: ChildProcess = spawn(+ cli.command,+ [...cli.args, "--mode", "rpc", "--no-session", "--model", "fakeprov/fake-model", "-e", APPROVAL_GUARD],+ {+ cwd: workspace,+ env: {+ ...process.env,+ HOME: dir,+ PI_CODING_AGENT_DIR: agentDir,+ FAKE_MCP_SERVER_CALLS: callsFile,+ [POLICY_ENV]: JSON.stringify(policy),+ },+ stdio: ["pipe", "pipe", "pipe"],+ },+ );+ cleanups.push(() => child.kill("SIGKILL"));+ const records: Rec[] = [];+ let stderr = "";+ const decoder = new JsonlDecoder((record) => records.push(record as Rec));+ child.stdout?.on("data", (chunk: Buffer) => decoder.push(chunk));+ child.stderr?.on("data", (chunk: Buffer) => {+ stderr += chunk.toString("utf8");+ });+ const send = (record: Rec) => child.stdin?.write(encodeRecord(record));+ const serverCalls = () =>+ existsSync(callsFile)+ ? readFileSync(callsFile, "utf8")+ .trim()+ .split("\n")+ .map((line) => (JSON.parse(line) as { name: string }).name)+ : [];+ return { child, records, send, serverCalls, mcpFile, stderr: () => stderr };+}++const engineAvailable = (() => {+ try {+ bundledMcpCli();+ return true;+ } catch {+ return false;+ }+})();++describe.skipIf(!engineAvailable)("approval guard in the real engine", () => {+ it("runs read-only tools, asks before sending, and blocks a declined send and a write to mcp.json", async () => {+ const engine = { mcp: "" };+ const model = await fakeModel([+ { name: "mcp__fake__list_messages", args: {} },+ { name: "mcp__fake__send_message", args: { to: "[email protected]", body: "Hello Bob" } },+ { name: "write", args: { path: "../agent/mcp.json", content: "{}" } },+ ]);+ cleanups.push(() => model.close());+ const { records, send, serverCalls, mcpFile, stderr } = startEngine(+ (model.address() as AddressInfo).port,+ );+ engine.mcp = readFileSync(mcpFile, "utf8");+ send({ type: "get_state", id: "s" });+ await waitFor(() => records.find((r) => r.id === "s"), 20_000).catch(() => {+ throw new Error(`the engine did not start: ${stderr().slice(-800)}`);+ });+ expect(stderr()).not.toMatch(/Failed to load extension/);++ // The MCP server connects in the background; prompt again until the model sees its tools.+ let prompts = 0;+ const ask = await waitFor(() => {+ const found = records.find((r) => r.type === "extension_ui_request" && r.method === "confirm");+ if (found) return found;+ if (records.filter((r) => r.type === "agent_settled").length >= prompts)+ send({ type: "prompt", id: `p${prompts++}`, message: "check my messages" });+ return undefined;+ }, 20_000);+ expect(ask).toMatchObject({+ title: "Allow Fake Chat to send message?",+ message: expect.stringContaining("to: [email protected]\nbody: Hello Bob"),+ });+ send({ type: "extension_ui_response", id: ask.id, confirmed: false });++ const ends = await waitFor(() => {+ const found = records.filter((r) => r.type === "tool_execution_end");+ return found.length >= 3 ? found : undefined;+ }, 20_000);+ const byTool = Object.fromEntries(ends.map((r) => [r.toolName, r]));+ const text = (r: Rec | undefined) => JSON.stringify((r?.result as Rec | undefined)?.content ?? r?.result);+ expect(byTool.mcp__fake__list_messages?.isError).toBe(false);+ expect(byTool.mcp__fake__send_message?.isError).toBe(true);+ expect(text(byTool.mcp__fake__send_message)).toContain("did not allow");+ expect(byTool.write?.isError).toBe(true);+ expect(text(byTool.write)).toContain("Connectors screen");+ expect(serverCalls()).toEqual(["list_messages"]);+ expect(readFileSync(mcpFile, "utf8")).toBe(engine.mcp);+ expect(records.filter((r) => r.type === "extension_ui_request" && r.method === "confirm")).toHaveLength(+ 1,+ );+ }, 60_000);+});diff --git a/packages/daemon/test/approval-guard.test.ts b/packages/daemon/test/approval-guard.test.tsnew file mode 100644index 0000000..a40c732--- /dev/null+++ b/packages/daemon/test/approval-guard.test.ts@@ -0,0 +1,275 @@+import { mkdtempSync, realpathSync, symlinkSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { describe, expect, it } from "vitest";+import approvalGuard, {+ type ConnectorPolicy,+ decide,+ isReadOnlyCall,+ POLICY_ENV,+ parsePolicy,+} from "../src/extensions/approval-guard.ts";++const AGENT = "/data/agent";+const PROTECTED = [`${AGENT}/mcp.json`, `${AGENT}/mcp-auth.json`, "/data/connectors.json", "/app/guard.ts"];++function policy(mode: "read_only" | "read_write" = "read_write"): ConnectorPolicy {+ return {+ connectors: { notion: { name: "Notion", mode, readOnlyTools: ["notion-search", "notion-fetch"] } },+ protectedPaths: PROTECTED,+ };+}++const call = (toolName: string, input: Record<string, unknown> = {}, readOnlyHint?: boolean) => ({+ toolName,+ input,+ cwd: "/data/workspace",+ ...(readOnlyHint === undefined ? {} : { readOnlyHint }),+});++describe("read-only classification (fail closed)", () => {+ it("needs both readOnlyHint true and the curated list", () => {+ const curated = ["notion-search"];+ expect(isReadOnlyCall("notion", "mcp__notion__notion_search", true, curated)).toBe(true);+ expect(isReadOnlyCall("notion", "mcp__notion__notion_search", false, curated)).toBe(false);+ expect(isReadOnlyCall("notion", "mcp__notion__notion_search", undefined, curated)).toBe(false);+ expect(isReadOnlyCall("notion", "mcp__notion__notion_search", "true", curated)).toBe(false);+ // Claimed read-only by the server, but not curated.+ expect(isReadOnlyCall("notion", "mcp__notion__notion_create_pages", true, curated)).toBe(false);+ // Another server's tool with the same short name.+ expect(isReadOnlyCall("notion", "mcp__linear__notion_search", true, curated)).toBe(false);+ });+});++describe("approval guard decisions", () => {+ it("lets curated read-only connector tools run in both modes", () => {+ for (const mode of ["read_only", "read_write"] as const) {+ expect(decide(call("mcp__notion__notion_search", { query: "plans" }, true), policy(mode))).toEqual({+ action: "pass",+ });+ }+ });++ it("asks before any other connector tool, with a readable, truncated preview", () => {+ const body = `Hello team,\n${"x".repeat(400)}`;+ const decision = decide(+ call("mcp__notion__notion_create_pages", { parent: "Weekly notes", title: "Plan", body, icon: "🚀" }),+ policy(),+ );+ expect(decision.action).toBe("ask");+ if (decision.action !== "ask") return;+ expect(decision.title).toBe("Allow Notion to create pages?");+ expect(decision.message).toContain("The assistant wants to create pages in Notion.");+ expect(decision.message).toContain("parent: Weekly notes");+ expect(decision.message).toContain("title: Plan");+ expect(decision.message).toContain("body: Hello team,\n xxx");+ expect(decision.message).toContain("…");+ expect(decision.message).not.toContain("x".repeat(300));+ // Key fields come before the rest.+ expect(decision.message.indexOf("parent:")).toBeLessThan(decision.message.indexOf("icon:"));+ expect(decision.message).not.toMatch(/gentle|\bpi\b|mcp__/i);+ });++ it("asks when a curated tool does not declare itself read-only", () => {+ expect(decide(call("mcp__notion__notion_fetch", { id: "p1" }), policy()).action).toBe("ask");+ expect(decide(call("mcp__notion__notion_fetch", { id: "p1" }, false), policy()).action).toBe("ask");+ });++ it("blocks write tools of a read-only connector and says how to change it", () => {+ const decision = decide(call("mcp__notion__notion_create_pages", { title: "x" }), policy("read_only"));+ expect(decision).toEqual({+ action: "block",+ reason: expect.stringContaining('switch Notion to "Read and send" in Connectors'),+ });+ });++ it("blocks tools of a server the user never approved", () => {+ const decision = decide(call("mcp__evil__send", { to: "x" }, true), policy());+ expect(decision).toEqual({ action: "block", reason: expect.stringContaining("not approved") });+ });++ it("asks for every connector tool when the policy is missing or was tampered with", () => {+ expect(parsePolicy(undefined)).toBeUndefined();+ expect(parsePolicy("{not json")).toBeUndefined();+ expect(parsePolicy(JSON.stringify({ connectors: { notion: { mode: "read_write" } } }))).toBeUndefined();+ const untrusted = parsePolicy("{}") ?? { protectedPaths: PROTECTED };+ expect(decide(call("mcp__notion__notion_search", { query: "q" }, true), untrusted).action).toBe("ask");+ expect(decide(call("mcp__evil__send", {}, true), untrusted).action).toBe("ask");+ expect(parsePolicy(JSON.stringify(policy()))).toEqual(policy());+ });++ it("leaves ordinary tools alone", () => {+ expect(decide(call("read", { path: `${AGENT}/mcp.json` }), policy())).toEqual({ action: "pass" });+ expect(decide(call("bash", { command: "ls -la" }), policy())).toEqual({ action: "pass" });+ expect(decide(call("write", { path: "notes.md", content: "mcp.json" }), policy())).toEqual({+ action: "pass",+ });+ });++ it("blocks edits of the connector control files, by absolute or relative path", () => {+ for (const input of [+ { path: `${AGENT}/mcp.json`, content: "{}" },+ { path: "../agent/mcp-auth.json", content: "{}" },+ { path: "/data/connectors.json", content: "{}" },+ { path: "/app/guard.ts", content: "" },+ ]) {+ for (const toolName of ["write", "edit"]) {+ expect(decide(call(toolName, input), policy())).toEqual({+ action: "block",+ reason: expect.stringContaining("Connectors screen"),+ });+ }+ }+ });++ it("sees through symlinked folders, for files that do not exist yet too", () => {+ const real = mkdtempSync(join(tmpdir(), "guard-"));+ const link = `${real}-link`;+ symlinkSync(real, link);+ const guarded: ConnectorPolicy = { connectors: {}, protectedPaths: [join(link, "mcp.json")] };+ for (const path of [+ join(real, "mcp.json"),+ join(realpathSync(real), "mcp.json"),+ join(link, "mcp.json"),+ ]) {+ expect(decide(call("write", { path, content: "{}" }), guarded).action).toBe("block");+ }+ expect(decide(call("bash", { command: `rm ${realpathSync(real)}/mcp.json` }), guarded).action).toBe(+ "block",+ );+ });++ it("blocks commands that change connectors or touch their files", () => {+ for (const command of [+ "pi mcp add slack --url https://example.com/mcp",+ "node cli.js mcp login notion",+ "pi mcp remove notion",+ "pi mcp logout notion",+ `cat > ${AGENT}/mcp.json <<'EOF'\n{}\nEOF`,+ "echo {} > $PI_CODING_AGENT_DIR/mcp.json",+ "sed -i '' s/read_only/read_write/ /data/connectors.json",+ ]) {+ expect(decide(call("bash", { command }), policy())).toEqual({+ action: "block",+ reason: expect.stringContaining("Connectors screen"),+ });+ }+ });+});++type Handler = (event: Record<string, unknown>, ctx: unknown) => Promise<unknown> | unknown;++function fakePi(tools: { name: string; annotations?: Record<string, boolean> }[]) {+ const handlers: Handler[] = [];+ return {+ handlers,+ pi: {+ on(event: string, handler: Handler) {+ if (event === "tool_call") handlers.push(handler);+ },+ getAllTools: () => tools,+ },+ };+}++function fakeCtx(answer: boolean | undefined, hasUI = true) {+ const asked: { title: string; message: string }[] = [];+ return {+ asked,+ ctx: {+ hasUI,+ cwd: "/data/workspace",+ ui: {+ confirm: async (title: string, message: string) => {+ asked.push({ title, message });+ return answer ?? false;+ },+ },+ },+ };+}++describe("approval guard extension", () => {+ const tools = [+ { name: "mcp__notion__notion_search", annotations: { readOnlyHint: true } },+ { name: "mcp__notion__notion_create_pages", annotations: { readOnlyHint: false } },+ ];++ function load(env: Record<string, string | undefined>) {+ const { pi, handlers } = fakePi(tools);+ const saved = process.env[POLICY_ENV];+ if (env[POLICY_ENV] === undefined) delete process.env[POLICY_ENV];+ else process.env[POLICY_ENV] = env[POLICY_ENV];+ try {+ approvalGuard(pi as never);+ } finally {+ if (saved === undefined) delete process.env[POLICY_ENV];+ else process.env[POLICY_ENV] = saved;+ }+ expect(handlers).toHaveLength(1);+ return handlers[0] as Handler;+ }++ it("reads the policy from its own environment and passes read-only tools without asking", async () => {+ const handler = load({ [POLICY_ENV]: JSON.stringify(policy()) });+ const { ctx, asked } = fakeCtx(true);+ const result = await handler(+ { type: "tool_call", toolName: "mcp__notion__notion_search", toolCallId: "t1", input: { query: "q" } },+ ctx,+ );+ expect(result).toBeUndefined();+ expect(asked).toEqual([]);+ });++ it("asks the user, runs on yes, and blocks on no, also for nested calls", async () => {+ const handler = load({ [POLICY_ENV]: JSON.stringify(policy()) });+ const event = {+ type: "tool_call",+ toolName: "mcp__notion__notion_create_pages",+ toolCallId: "p/1",+ parentToolCallId: "p",+ input: { title: "Plan" },+ };+ const yes = fakeCtx(true);+ expect(await handler(event, yes.ctx)).toBeUndefined();+ expect(yes.asked).toEqual([{ title: "Allow Notion to create pages?", message: expect.any(String) }]);+ const no = fakeCtx(false);+ expect(await handler(event, no.ctx)).toEqual({+ block: true,+ reason: expect.stringContaining("did not allow"),+ });+ expect(no.asked).toHaveLength(1);+ });++ it("blocks when nobody can approve", async () => {+ const handler = load({ [POLICY_ENV]: JSON.stringify(policy()) });+ const { ctx, asked } = fakeCtx(true, false);+ const result = await handler(+ { type: "tool_call", toolName: "mcp__notion__notion_create_pages", toolCallId: "t", input: {} },+ ctx,+ );+ expect(result).toEqual({ block: true, reason: expect.stringContaining("approval") });+ expect(asked).toEqual([]);+ });++ it("asks even for read-only tools when its policy was changed", async () => {+ const handler = load({ [POLICY_ENV]: '{"connectors":{"notion":"read_write"}}' });+ const { ctx, asked } = fakeCtx(false);+ const result = await handler(+ { type: "tool_call", toolName: "mcp__notion__notion_search", toolCallId: "t", input: { query: "q" } },+ ctx,+ );+ expect(result).toEqual({ block: true, reason: expect.any(String) });+ expect(asked).toHaveLength(1);+ });++ it("blocks a write to the connector files with a message for the assistant", async () => {+ const handler = load({ [POLICY_ENV]: JSON.stringify(policy()) });+ const { ctx } = fakeCtx(true);+ const result = await handler(+ { type: "tool_call", toolName: "write", toolCallId: "w", input: { path: `${AGENT}/mcp.json` } },+ ctx,+ );+ expect(result).toEqual({ block: true, reason: expect.stringContaining("Connectors screen") });+ });+});diff --git a/packages/daemon/test/connectors-gateway.test.ts b/packages/daemon/test/connectors-gateway.test.tsnew file mode 100644index 0000000..162e761--- /dev/null+++ b/packages/daemon/test/connectors-gateway.test.ts@@ -0,0 +1,162 @@+import { readFileSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { fileURLToPath } from "node:url";+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 { 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 GUARD = fileURLToPath(new URL("../src/extensions/approval-guard.ts", import.meta.url));++const daemons: DotDaemon[] = [];+afterEach(async () => {+ await Promise.all(daemons.splice(0).map((d) => d.close()));+});++async function setup(options: { home?: boolean; cliMode?: "auto" } = {}) {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ const envFile = join(dataDir, "agent-env.json");+ const argsFile = join(dataDir, "agent-args.json");+ const logs: string[] = [];+ 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],+ backoffMs: [50],+ agentEnv: {+ ...process.env,+ FAKE_AGENT_ENV_FILE: envFile,+ FAKE_AGENT_ARGS_FILE: argsFile,+ ...(options.cliMode ? { FAKE_MCP_CLI_MODE: options.cliMode } : {}),+ },+ ...(options.home ? { agentHome } : {}),+ authRuntime: async () => fake.runtime,+ connectorCli: { command: process.execPath, args: [FAKE_CLI] },+ log: (line) => logs.push(line),+ });+ daemons.push(d);+ const agentEnv = () => JSON.parse(readFileSync(envFile, "utf8")) as Record<string, string | undefined>;+ const agentArgs = () => JSON.parse(readFileSync(argsFile, "utf8")) as string[];+ return {+ d,+ dataDir,+ agentHome,+ logs,+ agentEnv,+ agentArgs,+ ...(await connect(d)),+ connect: () => 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 }));+ await waitFor(() => messages.some((m) => m.type === "ready"));+ 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 };+}++describe("connectors over the protocol", () => {+ it("lists the connectors, and /connectors opens the screen without reaching the assistant", async () => {+ const { send, find, messages } = await setup();+ send({ type: "connectors_list" });+ const list = await find("connectors");+ expect(list.connectors.map((c) => [c.id, c.status])).toEqual([+ ["notion", "off"],+ ["linear", "off"],+ ["atlassian", "off"],+ ]);+ expect(list.open).toBeUndefined();+ send({ type: "send", text: "/connectors" });+ expect((await find("connectors", (m) => m.open === true)).connectors).toHaveLength(3);+ expect(messages.some((m) => m.type === "user_message")).toBe(false);+ });++ it("connects: the sign-in goes to the window that asked, every window is refreshed, and the agent restarts with the new policy", async () => {+ const { d, send, find, agentEnv, connect: other } = await setup({ cliMode: "auto" });+ const second = await other();+ const pid = d.supervisor.pid;+ expect(JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}").connectors).toEqual({});+ send({ type: "connector_connect", connectorId: "notion" });+ const link = await find("auth_event", (m) => m.event.kind === "auth_url");+ expect(link.flowId).toMatch(/^connector-/);+ expect(await find("auth_done")).toMatchObject({ ok: true, providerId: "notion" });+ await second.find("connectors", (m) => m.connectors[0]?.status === "connected");+ expect(second.messages.some((m) => m.type === "auth_event" || m.type === "auth_done")).toBe(false);+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");+ await waitFor(() => JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}").connectors?.notion);+ expect(JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}").connectors.notion.mode).toBe(+ "read_only",+ );+ });++ it("waits for the running answer before restarting for a connector change", async () => {+ const { d, send, find } = await setup({ cliMode: "auto" });+ send({ type: "send", text: "hang" });+ await find("agent_state", (m) => m.state === "thinking");+ const pid = d.supervisor.pid;+ send({ type: "connector_connect", connectorId: "linear" });+ await find("auth_done");+ await new Promise((resolve) => setTimeout(resolve, 200));+ expect(d.supervisor.pid).toBe(pid);+ send({ type: "abort" });+ await waitFor(() => d.supervisor.pid !== pid && d.supervisor.state === "ready");+ });++ it("cancels a connector sign-in through auth_reply and refuses unknown connectors", async () => {+ const { send, find } = await setup();+ send({ type: "connector_connect", connectorId: "atlassian" });+ const prompt = await find("auth_prompt");+ send({ type: "auth_reply", flowId: prompt.prompt.flowId, cancelled: true });+ expect(await find("auth_done")).toMatchObject({ ok: false, message: "Sign-in cancelled." });+ send({ type: "connector_signin", connectorId: "gmail" });+ expect(await find("error", (m) => m.code === "unknown_connector")).toBeTruthy();+ });++ it("restores a changed mcp.json before the agent starts again", async () => {+ const { d, send, find, agentHome, logs } = await setup({ cliMode: "auto" });+ send({ type: "connector_connect", connectorId: "notion" });+ await find("auth_done");+ await waitFor(() => d.supervisor.state === "ready");+ const file = join(agentHome, "mcp.json");+ const approved = readFileSync(file, "utf8");+ writeFileSync(file, JSON.stringify({ mcpServers: { evil: { command: "sh", args: ["-c", "id"] } } }));+ await d.supervisor.restart();+ expect(readFileSync(file, "utf8")).toBe(approved);+ expect(logs.some((l) => l.includes("restored"))).toBe(true);+ });++ it("loads the approval guard into the assistant's own engine", async () => {+ const { agentArgs, agentEnv } = await setup({ home: true });+ const args = agentArgs();+ expect(args[args.indexOf("-e") + 1]).toBe(GUARD);+ expect(JSON.parse(agentEnv().GENTLE_DOT_CONNECTOR_POLICY ?? "{}")).toMatchObject({+ connectors: {},+ protectedPaths: expect.arrayContaining([GUARD]),+ });+ });+});diff --git a/packages/daemon/test/connectors.test.ts b/packages/daemon/test/connectors.test.tsnew file mode 100644index 0000000..60a3352--- /dev/null+++ b/packages/daemon/test/connectors.test.ts@@ -0,0 +1,420 @@+import { createHash } from "node:crypto";+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";+import { createRequire } from "node:module";+import { join } from "node:path";+import { fileURLToPath, pathToFileURL } from "node:url";+import type { ServerPayload } from "@gentle-dot/protocol";+import { afterEach, describe, expect, it } from "vitest";+import {+ bundledMcpCli,+ CATALOG,+ ConnectorManager,+ ConnectorStore,+ renderMcpJson,+} from "../src/connectors.ts";+import { isReadOnlyCall } from "../src/extensions/approval-guard.ts";+import { tempDir, waitFor } from "./helpers.ts";++const FAKE_CLI = fileURLToPath(new URL("./fixtures/fake-mcp-cli.ts", import.meta.url));+const NOTION_KEY = "mcp__notion|https://mcp.notion.com/mcp";++/** The engine's own MCP config validator, loaded by file path (the package exports only its entry). */+async function engineMcp() {+ const require = createRequire(import.meta.url);+ const file = (require.resolve.paths("@earendil-works/pi-coding-agent") ?? [])+ .map((dir) => join(dir, "@earendil-works", "pi-coding-agent", "dist", "core", "mcp-servers.js"))+ .find((path) => existsSync(path));+ if (!file) throw new Error("the engine package is missing");+ return (await import(pathToFileURL(file).href)) as {+ validateMcpServerConfig(name: string, raw: unknown): unknown;+ getMcpToolExposure(config: unknown, tool: string): string;+ };+}++describe("connectors catalog", () => {+ it("lists Notion, Linear, and Atlassian with their official remote servers", () => {+ expect(CATALOG.map(({ id, name, url }) => ({ id, name, url }))).toEqual([+ { id: "notion", name: "Notion", url: "https://mcp.notion.com/mcp" },+ { id: "linear", name: "Linear", url: "https://mcp.linear.app/mcp" },+ { id: "atlassian", name: "Atlassian", url: "https://mcp.atlassian.com/v2/mcp" },+ ]);+ for (const entry of CATALOG) {+ expect(entry.readOnlyTools.length).toBeGreaterThan(3);+ expect(entry.reads).not.toBe("");+ expect(entry.sends).not.toBe("");+ for (const tool of entry.readOnlyTools)+ expect(tool).not.toMatch(/create|update|edit|delete|send|add|move/i);+ }+ });++ it("classifies a tool as read-only only when the server says so and it is curated", () => {+ const notion = CATALOG.find((entry) => entry.id === "notion")?.readOnlyTools ?? [];+ expect(isReadOnlyCall("notion", "mcp__notion__notion_search", true, notion)).toBe(true);+ expect(isReadOnlyCall("notion", "mcp__notion__notion_search", undefined, notion)).toBe(false);+ expect(isReadOnlyCall("notion", "mcp__notion__notion_create_pages", true, notion)).toBe(false);+ const linear = CATALOG.find((entry) => entry.id === "linear")?.readOnlyTools ?? [];+ expect(isReadOnlyCall("linear", "mcp__linear__list_issues", true, linear)).toBe(true);+ expect(isReadOnlyCall("linear", "mcp__linear__create_issue", true, linear)).toBe(false);+ });+});++describe("mcp.json rendering", () => {+ it("renders direct servers the engine accepts; read only hides every tool but the curated ones", async () => {+ const { validateMcpServerConfig, getMcpToolExposure } = await engineMcp();+ const rendered = JSON.parse(+ renderMcpJson({+ connectors: {+ notion: { enabled: true, mode: "read_only" },+ linear: { enabled: true, mode: "read_write" },+ atlassian: { enabled: false, mode: "read_write" },+ unknown: { enabled: true, mode: "read_write" },+ },+ }),+ ) as { mcpServers: Record<string, Record<string, unknown>> };+ expect(Object.keys(rendered.mcpServers)).toEqual(["notion", "linear", "atlassian"]);+ expect(rendered.mcpServers.linear).toEqual({ url: "https://mcp.linear.app/mcp", exposure: "direct" });+ expect(rendered.mcpServers.atlassian).toEqual({+ url: "https://mcp.atlassian.com/v2/mcp",+ exposure: "direct",+ enabled: false,+ });+ const notion = rendered.mcpServers.notion;+ expect(notion).toMatchObject({ url: "https://mcp.notion.com/mcp", exposure: "direct" });+ for (const [name, config] of Object.entries(rendered.mcpServers)) {+ expect(typeof validateMcpServerConfig(name, config)).toBe("object");+ }+ expect(getMcpToolExposure(notion, "notion-search")).toBe("direct");+ expect(getMcpToolExposure(notion, "notion-create-pages")).toBe("hidden");+ expect(getMcpToolExposure(notion, "some-new-tool")).toBe("hidden");+ expect(getMcpToolExposure(rendered.mcpServers.linear, "create_issue")).toBe("direct");+ });++ it("renders an empty server list when nothing is added", () => {+ expect(JSON.parse(renderMcpJson({ connectors: {} }))).toEqual({ mcpServers: {} });+ });+});++describe("connector store", () => {+ function store() {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ mkdirSync(agentHome);+ const logs: string[] = [];+ return {+ dataDir,+ agentHome,+ logs,+ store: new ConnectorStore({ dataDir, agentHome, guardPath: "/app/guard.ts", log: (l) => logs.push(l) }),+ };+ }++ it("is the only writer: connectors.json keeps the approved mcp.json hash, both private", () => {+ const { store: s, dataDir, agentHome } = store();+ expect(s.ensureMcpJson()).toBe(false);+ expect(existsSync(join(agentHome, "mcp.json"))).toBe(false);+ s.update((state) => {+ state.connectors.notion = { enabled: true, mode: "read_only" };+ });+ const mcp = readFileSync(join(agentHome, "mcp.json"), "utf8");+ expect(JSON.parse(mcp).mcpServers.notion.url).toBe("https://mcp.notion.com/mcp");+ const saved = JSON.parse(readFileSync(join(dataDir, "connectors.json"), "utf8"));+ expect(saved).toEqual({+ version: 1,+ connectors: { notion: { enabled: true, mode: "read_only" } },+ hash: createHash("sha256").update(mcp).digest("hex"),+ });+ expect(statSync(join(dataDir, "connectors.json")).mode & 0o777).toBe(0o600);+ expect(statSync(join(agentHome, "mcp.json")).mode & 0o777).toBe(0o600);+ expect(readdirSync(agentHome).filter((f) => f.includes(".tmp"))).toEqual([]);+ expect(new ConnectorStore({ dataDir, agentHome }).state()).toEqual({+ connectors: { notion: { enabled: true, mode: "read_only" } },+ });+ });++ it("restores mcp.json when something else changed or deleted it", () => {+ const { store: s, agentHome, logs } = store();+ s.update((state) => {+ state.connectors.linear = { enabled: true, mode: "read_write" };+ });+ const file = join(agentHome, "mcp.json");+ const approved = readFileSync(file, "utf8");+ expect(s.ensureMcpJson()).toBe(false);+ writeFileSync(file, JSON.stringify({ mcpServers: { evil: { command: "sh" } } }));+ expect(s.ensureMcpJson()).toBe(true);+ expect(readFileSync(file, "utf8")).toBe(approved);+ rmSync(file);+ expect(s.ensureMcpJson()).toBe(true);+ expect(readFileSync(file, "utf8")).toBe(approved);+ expect(logs.filter((l) => l.includes("restored"))).toHaveLength(2);+ });++ it("restores the server list when mcp.json appears without any approved connector", () => {+ const { store: s, agentHome } = store();+ writeFileSync(join(agentHome, "mcp.json"), JSON.stringify({ mcpServers: { evil: { command: "sh" } } }));+ expect(s.ensureMcpJson()).toBe(true);+ expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8"))).toEqual({ mcpServers: {} });+ });++ it("gives the guard the curated lists, modes, and the files it must protect", () => {+ const { store: s, dataDir, agentHome } = store();+ s.update((state) => {+ state.connectors.notion = { enabled: true, mode: "read_write" };+ state.connectors.linear = { enabled: false, mode: "read_only" };+ });+ const policy = s.policy();+ expect(Object.keys(policy.connectors ?? {})).toEqual(["notion"]);+ expect(policy.connectors?.notion).toEqual({+ name: "Notion",+ mode: "read_write",+ readOnlyTools: CATALOG[0]?.readOnlyTools,+ });+ expect(policy.protectedPaths).toEqual([+ join(agentHome, "mcp.json"),+ join(agentHome, "mcp-auth.json"),+ join(dataDir, "connectors.json"),+ "/app/guard.ts",+ ]);+ });++ it("tells a stored sign-in from a pending one without exposing token values", () => {+ const { store: s, agentHome } = store();+ expect(s.isSignedIn("notion")).toBe(false);+ writeFileSync(join(agentHome, "mcp-auth.json"), "{oops");+ expect(s.isSignedIn("notion")).toBe(false);+ writeFileSync(+ join(agentHome, "mcp-auth.json"),+ JSON.stringify({ [NOTION_KEY]: { clientInformation: { client_id: "c" }, codeVerifier: "v" } }),+ );+ expect(s.isSignedIn("notion")).toBe(false);+ writeFileSync(+ join(agentHome, "mcp-auth.json"),+ JSON.stringify({ [NOTION_KEY]: { tokens: { access_token: "secret-token-value" } } }),+ );+ expect(s.isSignedIn("notion")).toBe(true);+ expect(s.isSignedIn("linear")).toBe(false);+ });+});++const managers: ConnectorManager[] = [];+afterEach(() => {+ for (const manager of managers.splice(0)) manager.cancelAll();+});++function setup(mode?: "fail" | "auto") {+ const dataDir = tempDir();+ const agentHome = join(dataDir, "agent");+ const cliLog = join(dataDir, "cli.jsonl");+ const logs: string[] = [];+ const store = new ConnectorStore({ dataDir, agentHome });+ const manager = new ConnectorManager({+ store,+ cli: { command: process.execPath, args: [FAKE_CLI] },+ env: {+ ...process.env,+ HOME: join(dataDir, "home"),+ FAKE_MCP_CLI_LOG: cliLog,+ ...(mode ? { FAKE_MCP_CLI_MODE: mode } : {}),+ },+ cwd: dataDir,+ log: (line) => logs.push(line),+ });+ managers.push(manager);+ const changes: boolean[] = [];+ manager.onChanged = (restart) => changes.push(restart);+ const owner = {};+ const sent: ServerPayload[] = [];+ const emit = (payload: ServerPayload) => sent.push(payload);+ const cliRuns = () =>+ existsSync(cliLog)+ ? readFileSync(cliLog, "utf8")+ .trim()+ .split("\n")+ .map((line) => JSON.parse(line) as { argv: string[]; pid: number; env: Record<string, string> })+ : [];+ function find<T extends ServerPayload["type"]>(+ type: T,+ where: (m: Extract<ServerPayload, { type: T }>) => boolean = () => true,+ ) {+ return waitFor(() =>+ sent.find(+ (m): m is Extract<ServerPayload, { type: T }> =>+ m.type === type && where(m as Extract<ServerPayload, { type: T }>),+ ),+ );+ }+ return { dataDir, agentHome, store, manager, changes, owner, sent, emit, find, logs, cliRuns };+}++const alive = (pid: number) => {+ try {+ process.kill(pid, 0);+ return true;+ } catch {+ return false;+ }+};++describe("connector sign-in", () => {+ it("finds the engine's own command line", () => {+ const cli = bundledMcpCli();+ expect(cli.command).toBe(process.execPath);+ expect(cli.args).toHaveLength(1);+ expect(cli.args[0]).toMatch(/pi-coding-agent[/\\]dist[/\\]bundle[/\\]cli\.js$/);+ expect(existsSync(cli.args[0] ?? "")).toBe(true);+ });++ it("lists every catalog connector with its status", () => {+ const { manager, store } = setup();+ expect(+ manager.list().map(({ id, added, enabled, mode, status }) => ({ id, added, enabled, mode, status })),+ ).toEqual([+ { id: "notion", added: false, enabled: false, mode: "read_only", status: "off" },+ { id: "linear", added: false, enabled: false, mode: "read_only", status: "off" },+ { id: "atlassian", added: false, enabled: false, mode: "read_only", status: "off" },+ ]);+ expect(manager.list()[0]).toMatchObject({+ name: "Notion",+ reads: expect.any(String),+ sends: expect.any(String),+ });+ store.update((state) => {+ state.connectors.linear = { enabled: true, mode: "read_write" };+ });+ expect(manager.list()[1]).toMatchObject({+ added: true,+ enabled: true,+ mode: "read_write",+ status: "needs_signin",+ });+ });++ it("connects: adds the server, relays the sign-in link, finishes through a pasted address", async () => {+ const { manager, store, agentHome, dataDir, changes, owner, emit, find, sent, logs, cliRuns } = setup();+ expect(manager.connect(owner, "notion", emit)).toBeUndefined();+ expect(store.state().connectors.notion).toEqual({ enabled: true, mode: "read_only" });+ expect(changes).toEqual([true]);+ const link = await find("auth_event", (m) => m.event.kind === "auth_url");+ expect(link.flowId).toMatch(/^connector-/);+ expect(link.event).toMatchObject({+ kind: "auth_url",+ url: expect.stringMatching(/^https:\/\/auth\.example\.com\/authorize\?/),+ instructions: expect.stringContaining("Notion"),+ });+ const prompt = await find("auth_prompt");+ expect(prompt.prompt).toMatchObject({ flowId: link.flowId, kind: "manual_code" });+ const [run] = cliRuns();+ expect(run?.argv).toEqual(["mcp", "login", "notion"]);+ expect(run?.env).toEqual({ PI_CODING_AGENT_DIR: agentHome, HOME: join(dataDir, "home") });+ const redirect = new URL(+ new URL(link.event.kind === "auth_url" ? link.event.url : "").searchParams.get("redirect_uri") ?? "",+ );+ redirect.searchParams.set("code", "very-secret-code");+ redirect.searchParams.set("state", "fake-state");+ expect(manager.reply(owner, link.flowId, { value: redirect.href })).toBe(true);+ const done = await find("auth_done");+ expect(done).toEqual({ type: "auth_done", flowId: link.flowId, providerId: "notion", ok: true });+ expect(manager.list()[0]?.status).toBe("connected");+ expect(changes).toEqual([true, false]);+ expect(logs.join("\n")).not.toContain("very-secret-code");+ expect(JSON.stringify(sent)).not.toContain("very-secret-code");+ expect(JSON.stringify(sent)).not.toContain("fake-access-token-value");+ await waitFor(() => !alive(run?.pid ?? 0));+ });++ it("refuses a pasted address for another place or sign-in, keeps waiting, and cancels by stopping the process", async () => {+ const { manager, owner, emit, find, sent, cliRuns } = setup();+ manager.connect(owner, "notion", emit);+ const link = await find("auth_event", (m) => m.event.kind === "auth_url");+ await find("auth_prompt");+ const url = new URL(link.event.kind === "auth_url" ? link.event.url : "");+ const redirect = new URL(url.searchParams.get("redirect_uri") ?? "");+ for (const pasted of [+ `${redirect.href}?code=c&state=other-state`,+ `https://evil.example.com${redirect.pathname}?code=c&state=fake-state`,+ "not a url",+ ]) {+ const before = sent.filter((m) => m.type === "auth_prompt").length;+ expect(manager.reply(owner, link.flowId, { value: pasted })).toBe(true);+ await waitFor(() => sent.filter((m) => m.type === "auth_prompt").length > before);+ }+ expect(sent.some((m) => m.type === "auth_done")).toBe(false);+ expect(manager.reply({}, link.flowId, { cancelled: true })).toBe(false);+ const pid = cliRuns()[0]?.pid ?? 0;+ expect(alive(pid)).toBe(true);+ expect(manager.reply(owner, link.flowId, { cancelled: true })).toBe(true);+ const done = await find("auth_done");+ expect(done).toMatchObject({ ok: false, message: "Sign-in cancelled." });+ await waitFor(() => !alive(pid));+ expect(manager.list()[0]?.status).toBe("needs_signin");+ });++ it("runs one sign-in at a time", async () => {+ const { manager, owner, emit, find } = setup();+ manager.connect(owner, "notion", emit);+ await find("auth_prompt");+ expect(manager.connect(owner, "linear", emit)).toMatchObject({ code: "connector_busy" });+ expect(manager.signIn(owner, "notion", emit)).toMatchObject({ code: "connector_busy" });+ expect(manager.signIn(owner, "linear", emit)).toMatchObject({ code: "connector_busy" });+ manager.cancelOwnedBy(owner);+ await find("auth_done");+ await waitFor(() => manager.signIn(owner, "notion", emit) === undefined);+ });++ it("reports a failed sign-in in plain words and marks the connector", async () => {+ const { manager, owner, emit, find, logs } = setup("fail");+ manager.connect(owner, "notion", emit);+ const done = await find("auth_done");+ expect(done).toMatchObject({ ok: false, message: "Sign-in did not finish. Please try again." });+ expect(manager.list()[0]?.status).toBe("error");+ expect(logs.some((l) => l.includes("notion") && l.includes("exit 1"))).toBe(true);+ expect(logs.join("\n")).not.toContain("https://auth.example.com");+ });++ it("signs in again without changing the configuration, when the browser callback arrives", async () => {+ const { manager, store, owner, emit, find, changes } = setup("auto");+ store.update((state) => {+ state.connectors.notion = { enabled: true, mode: "read_write" };+ });+ expect(manager.signIn(owner, "notion", emit)).toBeUndefined();+ expect((await find("auth_done")).ok).toBe(true);+ expect(changes).toEqual([false]);+ expect(manager.signIn(owner, "atlassian", emit)).toMatchObject({ code: "connector_not_added" });+ expect(manager.signIn(owner, "nope", emit)).toMatchObject({ code: "unknown_connector" });+ });++ it("turns a connector off, changes its mode, and removes it with a sign-out", async () => {+ const { manager, store, owner, emit, find, sent, changes, agentHome, cliRuns } = setup("auto");+ manager.connect(owner, "notion", emit);+ await find("auth_done");+ expect(manager.setMode("notion", "read_write")).toBeUndefined();+ expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8")).mcpServers.notion).toEqual({+ url: "https://mcp.notion.com/mcp",+ exposure: "direct",+ });+ expect(manager.disconnect("notion")).toBeUndefined();+ expect(manager.list()[0]).toMatchObject({ added: true, enabled: false, status: "off" });+ expect(changes).toEqual([true, false, true, true]);+ // Turning it on again needs no new sign-in; the window still hears that it is done.+ const before = sent.length;+ expect(manager.connect(owner, "notion", emit)).toBeUndefined();+ expect(sent.slice(before)).toEqual([+ { type: "auth_done", flowId: expect.stringMatching(/^connector-/), providerId: "notion", ok: true },+ ]);+ expect(manager.list()[0]).toMatchObject({ enabled: true, status: "connected" });+ expect(cliRuns()).toHaveLength(1);+ expect(manager.disconnect("notion")).toBeUndefined();+ changes.splice(4);+ expect(await manager.remove("notion")).toBeUndefined();+ expect(cliRuns().map((r) => r.argv)).toEqual([+ ["mcp", "login", "notion"],+ ["mcp", "logout", "notion"],+ ]);+ expect(store.state().connectors).toEqual({});+ expect(JSON.parse(readFileSync(join(agentHome, "mcp.json"), "utf8"))).toEqual({ mcpServers: {} });+ expect(JSON.parse(readFileSync(join(agentHome, "mcp-auth.json"), "utf8"))).toEqual({});+ expect(manager.list()[0]).toMatchObject({ added: false, status: "off" });+ expect(changes).toEqual([true, false, true, true, true]);+ expect(manager.setMode("notion", "read_only")).toMatchObject({ code: "connector_not_added" });+ expect(await manager.remove("nope")).toMatchObject({ code: "unknown_connector" });+ });+});diff --git a/packages/daemon/test/fixtures/fake-agent.ts b/packages/daemon/test/fixtures/fake-agent.tsindex 93c2c2b..0221305 100644--- a/packages/daemon/test/fixtures/fake-agent.ts+++ b/packages/daemon/test/fixtures/fake-agent.ts@@ -6,12 +6,14 @@// "tool:<name>" runs one fake tool call// "ask:select" asks a select dialog and echoes the answer// "ask:confirm" asks a confirm dialog and echoes the answer+// "ask:approval" asks the approval guard's real confirm for a Notion page, and echoes the answer// "hang" starts a run that only ends on abort (an aborted answer), or on a// session switch (Pi then ends it with an error: "This operation was aborted")// "fail" the provider fails: an answer that ends with stopReason "error"// "slow" answers after 1.5 s, leaving time to queue messages// "crash" starts a run and exits with code 1// "burst" answers and finishes the run in a single stdout write+// "burst:<text>" runs <text> the same way: the prompt's response and the whole run in one write// "compact" records a compaction entry (its summary lists the user's messages so far)// "pad:<n>" grows the session file by about n bytes (an entry outside the context)// "recall" answers with the hidden context messages it was given@@ -78,6 +80,7 @@ if (process.env.FAKE_AGENT_ENV_FILE) {"ENGRAM_PORT","ENGRAM_URL","ENGRAM_DATA_DIR",+ "GENTLE_DOT_CONNECTOR_POLICY",].map((key) => [key, process.env[key]]),),),@@ -309,6 +312,28 @@ async function runPrompt(text: string) {assistantText(answer.confirmed ? "Confirmed" : "Declined");return endRun();}+ if (text === "ask:approval") {+ const { decide } = await import("../../src/extensions/approval-guard.ts");+ const decision = decide(+ {+ toolName: "mcp__notion__notion_create_pages",+ input: {+ parent: "Team notes",+ title: "Weekly plan",+ content: "Monday: review the launch checklist.\nTuesday: send the update to the team.",+ },+ cwd: process.cwd(),+ },+ {+ connectors: { notion: { name: "Notion", mode: "read_write", readOnlyTools: [] } },+ protectedPaths: [],+ },+ );+ if (decision.action !== "ask") throw new Error("the guard did not ask");+ const answer = await askUi({ method: "confirm", title: decision.title, message: decision.message });+ assistantText(answer.confirmed ? "Created the page" : "I did not create the page");+ return endRun();+ }assistantText(`Echo: ${text}`);endRun();}@@ -354,9 +379,10 @@ function handle(rec: Rec) {return respond(id, "prompt", { disposition: "queued" });}if (process.env.FAKE_AGENT_NO_MODEL) return respond(id, "prompt", undefined, "No model selected");- if (rec.message === "burst") batch = [];+ const burst = String(rec.message).startsWith("burst");+ if (burst) batch = [];respond(id, "prompt", { disposition: "started" });- void run(String(rec.message));+ void run(burst ? String(rec.message).replace(/^burst:/, "") : String(rec.message));if (batch) {process.stdout.write(batch.join(""));batch = undefined;diff --git a/packages/daemon/test/fixtures/fake-mcp-cli.ts b/packages/daemon/test/fixtures/fake-mcp-cli.tsnew file mode 100644index 0000000..c9a7e9d--- /dev/null+++ b/packages/daemon/test/fixtures/fake-mcp-cli.ts@@ -0,0 +1,82 @@+#!/usr/bin/env node+// A stand-in for the engine's `mcp login <server>` and `mcp logout <server>` commands.+// login prints the authorization URL like the engine does, then waits on a loopback+// callback (`/callback?code=…&state=fake-state`); on that request it stores a sign-in+// in `<PI_CODING_AGENT_DIR>/mcp-auth.json` under `mcp__<server>|<url>` and exits 0.+// logout removes that key. Environment:+// FAKE_MCP_CLI_LOG append {argv, env} as JSONL for every run+// FAKE_MCP_CLI_MODE "fail": exit 1 after printing the URL; "auto": finish without a callback+// FAKE_MCP_CLI_URL the server URL stored with the sign-in (default Notion's)+import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs";+import { createServer } from "node:http";+import { join } from "node:path";++const [command, name] = process.argv.slice(2).filter((arg) => arg !== "mcp");+const agentDir = process.env.PI_CODING_AGENT_DIR ?? ".";+const authFile = join(agentDir, "mcp-auth.json");+const key = `mcp__${name}|${process.env.FAKE_MCP_CLI_URL ?? "https://mcp.notion.com/mcp"}`;++if (process.env.FAKE_MCP_CLI_LOG) {+ appendFileSync(+ process.env.FAKE_MCP_CLI_LOG,+ `${JSON.stringify({+ argv: process.argv.slice(2),+ pid: process.pid,+ env: { PI_CODING_AGENT_DIR: process.env.PI_CODING_AGENT_DIR, HOME: process.env.HOME },+ })}\n`,+ );+}++function readAuth(): Record<string, unknown> {+ return existsSync(authFile) ? (JSON.parse(readFileSync(authFile, "utf8")) as Record<string, unknown>) : {};+}++if (command === "logout") {+ const states = readAuth();+ const had = key in states;+ delete states[key];+ writeFileSync(authFile, JSON.stringify(states));+ console.log(+ had ? `Signed out of MCP server "${name}".` : `No stored credentials for MCP server "${name}".`,+ );+ process.exit(0);+}++if (command !== "login") {+ console.error(`Unknown mcp command "${command}".`);+ process.exit(1);+}++const server = createServer((req, res) => {+ const url = new URL(req.url ?? "/", "http://127.0.0.1");+ if (url.pathname !== "/callback" || url.searchParams.get("state") !== "fake-state") {+ res.writeHead(400).end("bad callback");+ return;+ }+ res.writeHead(200).end("You can close this page.");+ finish();+});++function finish(): void {+ const states = readAuth();+ states[key] = { tokens: { access_token: "fake-access-token-value", token_type: "Bearer" } };+ writeFileSync(authFile, JSON.stringify(states));+ console.log(`Signed in to MCP server "${name}" (3 tools).`);+ server.close();+ process.exit(0);+}++server.listen(0, "127.0.0.1", () => {+ const { port } = server.address() as { port: number };+ const redirect = encodeURIComponent(`http://127.0.0.1:${port}/callback`);+ console.log(+ `Sign in to MCP server "${name}" in your browser:\nhttps://auth.example.com/authorize?response_type=code&client_id=fake&state=fake-state&redirect_uri=${redirect}`,+ );+ if (process.env.FAKE_MCP_CLI_MODE === "fail") {+ setTimeout(() => {+ console.error(`Sign-in to MCP server "${name}" failed: invalid_client for https://auth.example.com/x`);+ process.exit(1);+ }, 150);+ }+ if (process.env.FAKE_MCP_CLI_MODE === "auto") setTimeout(finish, 150);+});diff --git a/packages/daemon/test/fixtures/fake-mcp-server.ts b/packages/daemon/test/fixtures/fake-mcp-server.tsnew file mode 100644index 0000000..f760d81--- /dev/null+++ b/packages/daemon/test/fixtures/fake-mcp-server.ts@@ -0,0 +1,59 @@+#!/usr/bin/env node+// A minimal MCP server over stdio (newline-delimited JSON-RPC) with two tools: `list_messages`,+// which declares itself read-only, and `send_message`, which does not. Each call is appended to+// FAKE_MCP_SERVER_CALLS as JSONL, so a test can tell which calls really ran.+import { appendFileSync } from "node:fs";++type Request = { jsonrpc: "2.0"; id?: number | string; method: string; params?: Record<string, unknown> };++const TOOLS = [+ {+ name: "list_messages",+ description: "List recent messages.",+ inputSchema: { type: "object", properties: {} },+ annotations: { readOnlyHint: true },+ },+ {+ name: "send_message",+ description: "Send a message.",+ inputSchema: { type: "object", properties: { to: { type: "string" }, body: { type: "string" } } },+ annotations: { readOnlyHint: false },+ },+];++function reply(id: Request["id"], result: unknown): void {+ process.stdout.write(`${JSON.stringify({ jsonrpc: "2.0", id, result })}\n`);+}++let buffer = "";+process.stdin.on("data", (chunk: Buffer) => {+ buffer += chunk.toString("utf8");+ for (let index = buffer.indexOf("\n"); index >= 0; index = buffer.indexOf("\n")) {+ const line = buffer.slice(0, index).trim();+ buffer = buffer.slice(index + 1);+ if (line) handle(JSON.parse(line) as Request);+ }+});++function handle(request: Request): void {+ if (request.id === undefined) return;+ switch (request.method) {+ case "initialize":+ reply(request.id, {+ protocolVersion: request.params?.protocolVersion ?? "2025-06-18",+ capabilities: { tools: {} },+ serverInfo: { name: "fake", version: "1.0.0" },+ });+ return;+ case "tools/list":+ reply(request.id, { tools: TOOLS });+ return;+ case "tools/call":+ if (process.env.FAKE_MCP_SERVER_CALLS)+ appendFileSync(process.env.FAKE_MCP_SERVER_CALLS, `${JSON.stringify(request.params)}\n`);+ reply(request.id, { content: [{ type: "text", text: `ran ${String(request.params?.name)}` }] });+ return;+ default:+ reply(request.id, {});+ }+}diff --git a/packages/daemon/test/gateway.test.ts b/packages/daemon/test/gateway.test.tsindex e5c51fb..7cd507d 100644--- a/packages/daemon/test/gateway.test.ts+++ b/packages/daemon/test/gateway.test.ts@@ -527,6 +527,8 @@ describe("own instance", () => {// The user's global Engram: its data dir, so the memory plugin accepts the user's server.ENGRAM_DATA_DIR: join(realHome, ".engram"),ENGRAM_URL: "http://127.0.0.1:7437",+ // The approval guard's policy: no connector is on yet.+ GENTLE_DOT_CONNECTOR_POLICY: expect.stringContaining('"connectors":{}'),});expect(statSync(home).mode & 0o777).toBe(0o700);expect(existsSync(join(dataDir, "workspace"))).toBe(true);diff --git a/packages/daemon/test/rotation.test.ts b/packages/daemon/test/rotation.test.tsindex 68f3076..fd09f2f 100644--- a/packages/daemon/test/rotation.test.ts+++ b/packages/daemon/test/rotation.test.ts@@ -94,6 +94,18 @@ describe("transparent rotation", () => {expect(answers().at(-1)).toContain("keep this in mind: blue");});+ it("rotates once when the run settles in the same write as the prompt's answer", async () => {+ const { supervisor, bridge, client, received } = await setup({ limits: { bytes: 3000 } });+ const first = supervisor.sessionFile as string;+ // The answer to the prompt and the whole run, up to agent_settled, arrive together.+ await bridge.handle(client, { type: "send", text: "burst:pad:4000" });+ await waitFor(() => supervisor.sessionFile !== first);+ await new Promise((resolve) => setTimeout(resolve, 300));+ expect(supervisor.previousSessions).toEqual([first]);+ const marked = received.filter((p) => p.type === "history" && p.messages.some((m) => m.earlier));+ expect(marked).toHaveLength(1);+ });+it("keeps the chain of session files across a restart of the daemon", async () => {const { supervisor, dataDir, say } = await setup({ limits: { compactions: 1 } });const first = supervisor.sessionFile as string;@@ -135,13 +147,15 @@ describe("transparent rotation", () => {const first = supervisor.sessionFile as string;await say("compact");await waitFor(() => logs.some((line) => line.includes("fresh session")));- const current = supervisor.sessionFile as string;- expect(current).not.toBe(first);+ const seed = logs.join("\n").match(/handoff session (\S+\.jsonl)/)?.[1];+ // The log comes before the engine is asked for the fresh session.+ const current = await waitFor(+ () => supervisor.sessionFile !== first && supervisor.sessionFile !== seed && supervisor.sessionFile,+ );expect(headerOf(current)).toMatchObject({ parentSession: first });expect(supervisor.previousSessions).toEqual([first]);// The handoff file the engine could not use stays on disk.- const seed = logs.join("\n").match(/handoff session (\S+\.jsonl)/)?.[1];- expect(seed && seed !== current && existsSync(seed)).toBe(true);+ expect(seed && existsSync(seed)).toBe(true);await say("after");expect(answers().at(-1)).toBe("Echo: after");});diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex 887f4cb..8bcd49d 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -86,6 +86,26 @@ export type AuthEvent =| { kind: "device_code"; userCode: string; verificationUri: string; expiresInSeconds?: number }| { kind: "progress"; message: string };+/** What a connector may do: only read, or also act after the user approves each action. */+export type ConnectorMode = "read_only" | "read_write";++/** `off`: not added or turned off; `error`: the last sign-in failed. */+export type ConnectorStatus = "off" | "needs_signin" | "connected" | "error";++/** A service the assistant can connect to (an MCP server the daemon manages). */+export interface ConnectorInfo {+ id: string;+ name: string;+ /** What it can read, in plain words. */+ reads: string;+ /** What it can do in "Read and send" mode. */+ sends: string;+ added: boolean;+ enabled: boolean;+ mode: ConnectorMode;+ status: ConnectorStatus;+}+/** Reasoning effort levels the engine accepts. */export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;export type ThinkingLevel = (typeof THINKING_LEVELS)[number];@@ -178,7 +198,13 @@ export type ClientMessage =| { type: "profile_delete"; name: string }| { type: "profile_apply"; name: string }| { type: "profile_import" }- | { type: "profile_save_current"; name: string };+ | { type: "profile_save_current"; name: string }+ | { type: "connectors_list" }+ | {+ type: "connector_connect" | "connector_signin" | "connector_disconnect" | "connector_remove";+ connectorId: string;+ }+ | { type: "connector_mode"; connectorId: string; mode: ConnectorMode };export type ServerPayload =| { type: "ready"; agentState: AgentState; conversationId?: string; model?: string; features?: Features }@@ -225,7 +251,9 @@ export type ServerPayload =/** Set when the user typed `/profiles`. */open?: boolean;}- | { type: "profiles_imported"; imported: { from: string; to: string }[]; missingProviders: string[] };+ | { type: "profiles_imported"; imported: { from: string; to: string }[]; missingProviders: string[] }+ /** Connector sign-ins reuse `auth_event`, `auth_prompt`, and `auth_done`, with flow ids starting `connector-`. */+ | { type: "connectors"; connectors: ConnectorInfo[]; open?: boolean };/** Every daemon message carries a per-connection, monotonic `seq`. */export type ServerMessage = ServerPayload & { seq: number };@@ -233,6 +261,8 @@ export type ServerMessage = ServerPayload & { seq: number };const isString = (value: unknown): value is string => typeof value === "string";const isOptional = (value: unknown, check: (v: unknown) => boolean) => value === undefined || check(value);const MAX_TEXT = 100_000;+const CONNECTOR_ID = /^[a-z0-9][a-z0-9-]{0,39}$/;+const isConnectorId = (value: unknown): value is string => isString(value) && CONNECTOR_ID.test(value);/*** Reads the complete queues from the engine's `queue_update` record. A missing@@ -318,6 +348,16 @@ export function parseClientMessage(raw: string): ClientMessage | undefined {case "profile_apply":case "profile_save_current":return isValidProfileName(m.name) ? { type: m.type, name: m.name } : undefined;+ case "connector_connect":+ case "connector_signin":+ case "connector_disconnect":+ case "connector_remove":+ return isConnectorId(m.connectorId) ? { type: m.type, connectorId: m.connectorId } : undefined;+ case "connector_mode":+ return isConnectorId(m.connectorId) && (m.mode === "read_only" || m.mode === "read_write")+ ? { type: "connector_mode", connectorId: m.connectorId, mode: m.mode }+ : undefined;+ case "connectors_list":case "profiles_list":case "profile_import":case "abort":diff --git a/packages/protocol/test/protocol.test.ts b/packages/protocol/test/protocol.test.tsindex 132814d..c2603b1 100644--- a/packages/protocol/test/protocol.test.ts+++ b/packages/protocol/test/protocol.test.ts@@ -184,3 +184,43 @@ describe("profile messages", () => {expect(THINKING_LEVELS).toEqual(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);});});++describe("connector messages", () => {+ it("accepts every connector command", () => {+ expect(parseClientMessage('{"type":"connectors_list"}')).toEqual({ type: "connectors_list" });+ for (const type of [+ "connector_connect",+ "connector_signin",+ "connector_disconnect",+ "connector_remove",+ ]) {+ expect(parseClientMessage(JSON.stringify({ type, connectorId: "notion" }))).toEqual({+ type,+ connectorId: "notion",+ });+ }+ expect(+ parseClientMessage('{"type":"connector_mode","connectorId":"linear","mode":"read_write"}'),+ ).toEqual({ type: "connector_mode", connectorId: "linear", mode: "read_write" });+ expect(parseClientMessage('{"type":"connector_mode","connectorId":"linear","mode":"read_only"}')).toEqual(+ {+ type: "connector_mode",+ connectorId: "linear",+ mode: "read_only",+ },+ );+ });++ it("rejects bad connector ids and modes", () => {+ expect(parseClientMessage('{"type":"connector_connect"}')).toBeUndefined();+ expect(parseClientMessage('{"type":"connector_connect","connectorId":"../x"}')).toBeUndefined();+ expect(parseClientMessage('{"type":"connector_remove","connectorId":"__proto__"}')).toBeUndefined();+ expect(+ parseClientMessage(`{"type":"connector_signin","connectorId":"${"a".repeat(41)}"}`),+ ).toBeUndefined();+ expect(+ parseClientMessage('{"type":"connector_mode","connectorId":"notion","mode":"all"}'),+ ).toBeUndefined();+ expect(parseClientMessage('{"type":"connector_mode","connectorId":"notion"}')).toBeUndefined();+ });+});diff --git a/packages/ui/src/accounts.css b/packages/ui/src/accounts.cssindex 04a75d0..3fbf202 100644--- a/packages/ui/src/accounts.css+++ b/packages/ui/src/accounts.css@@ -67,3 +67,56 @@ button.back {margin: 2px 0 4px;font-size: 12px;}++/* Connectors screen (ConnectorsPanel). */++.connector-note {+ margin: 0 0 4px;+ font-size: 12px;+ line-height: 17px;+ color: var(--muted);+}++.connector-mode {+ display: flex;+ flex-wrap: wrap;+ gap: 6px 14px;+ margin: 8px 0 10px;+ padding: 0;+ border: none;+}++.connector-mode legend {+ position: absolute;+ width: 1px;+ height: 1px;+ overflow: hidden;+ clip-path: inset(50%);+}++.connector-mode label {+ display: flex;+ align-items: center;+ gap: 6px;+ font-size: 13px;+}++.connector-mode input {+ accent-color: var(--accent);+}++.chip.connector-needs_signin {+ color: var(--yellow);+ border-color: rgba(224, 194, 122, 0.45);+}++.chip.connector-error {+ color: var(--red);+ border-color: rgba(255, 113, 143, 0.45);+}++.chip.connector-connected {+ border-color: rgba(180, 231, 199, 0.3);+ background: rgba(180, 231, 199, 0.1);+ color: var(--green);+}diff --git a/packages/ui/src/components/AccountsPanel.tsx b/packages/ui/src/components/AccountsPanel.tsxindex 2c19d00..6e410de 100644--- a/packages/ui/src/components/AccountsPanel.tsx+++ b/packages/ui/src/components/AccountsPanel.tsx@@ -228,7 +228,7 @@ function ProviderSection({ title, hint, providers, label, plan, action, send }:);}-function FlowEvent({ event, openUrl }: { event: AuthEvent; openUrl: (url: string) => void }) {+export function FlowEvent({ event, openUrl }: { event: AuthEvent; openUrl: (url: string) => void }) {switch (event.kind) {case "auth_url":return (@@ -255,7 +255,7 @@ function FlowEvent({ event, openUrl }: { event: AuthEvent; openUrl: (url: string}}-function FlowPrompt({ prompt, send }: { prompt: AuthPrompt; send: Send }) {+export function FlowPrompt({ prompt, send }: { prompt: AuthPrompt; send: Send }) {const [value, setValue] = useState("");const answer = (text: string) => send({ type: "auth_reply", flowId: prompt.flowId, value: text });if (prompt.kind === "select") {diff --git a/packages/ui/src/components/ChatSurface.tsx b/packages/ui/src/components/ChatSurface.tsxindex db87a12..402beb0 100644--- a/packages/ui/src/components/ChatSurface.tsx+++ b/packages/ui/src/components/ChatSurface.tsx@@ -5,7 +5,16 @@ import { activeTitle, type DotAction, type DotState, isBusy, needsAccount } fromimport { AccountsPanel } from "./AccountsPanel.tsx";import { AskCard } from "./AskCard.tsx";import { Composer } from "./Composer.tsx";-import { AccountsIcon, ConversationsIcon, MinusIcon, PlusIcon, ProfilesIcon, RoseGlyph } from "./icons.tsx";+import { ConnectorsPanel } from "./ConnectorsPanel.tsx";+import {+ AccountsIcon,+ ConnectorsIcon,+ ConversationsIcon,+ MinusIcon,+ PlusIcon,+ ProfilesIcon,+ RoseGlyph,+} from "./icons.tsx";import { MessageList } from "./MessageList.tsx";import { ProfilesPanel } from "./ProfilesPanel.tsx";import { newRequestId, type Send } from "./types.ts";@@ -54,6 +63,10 @@ export function ChatSurface({send({ type: "profiles_list" });dispatch({ type: "profiles", open: true });};+ const openConnectors = () => {+ send({ type: "connectors_list" });+ dispatch({ type: "connectors", open: true });+ };const [showConversations, setShowConversations] = useState(false);/** A switch that waits for the user to confirm stopping the running answer. */const [pendingSwitch, setPendingSwitch] = useState<SwitchMessage | undefined>(undefined);@@ -67,8 +80,10 @@ export function ChatSurface({setShowConversations(false);if (state.auth.open && !state.auth.flow?.prompt) dispatch({ type: "accounts", open: false });if (state.profiles.open) dispatch({ type: "profiles", open: false });+ if (state.connectors.open && !state.connectors.flow?.prompt)+ dispatch({ type: "connectors", open: false });};- const covered = state.auth.open || state.profiles.open;+ const covered = state.auth.open || state.profiles.open || state.connectors.open;// One continuous chat unless the daemon turns the conversations list on.const conversations = state.features.conversations;const status = statusText(state);@@ -108,6 +123,15 @@ export function ChatSurface({<button type="button" className="icon" aria-label="Profiles" title="Profiles" onClick={openProfiles}><ProfilesIcon /></button>+ <button+ type="button"+ className="icon"+ aria-label="Connectors"+ title="Connectors"+ onClick={openConnectors}+ >+ <ConnectorsIcon />+ </button>{conversations ? (<buttontype="button"@@ -173,6 +197,12 @@ export function ChatSurface({</main>) : null}+ {state.connectors.open && !state.auth.open && !state.profiles.open ? (+ <main className="chat-body">+ <ConnectorsPanel connectors={state.connectors} send={send} dispatch={dispatch} openUrl={openUrl} />+ </main>+ ) : null}+{!covered && needsAccount(state) ? (<div className="onboarding"><p>To start, connect the AI service you use (a subscription or an API key).</p>diff --git a/packages/ui/src/components/ConnectorsPanel.tsx b/packages/ui/src/components/ConnectorsPanel.tsxnew file mode 100644index 0000000..dcc837f--- /dev/null+++ b/packages/ui/src/components/ConnectorsPanel.tsx@@ -0,0 +1,175 @@+import type { ConnectorInfo, ConnectorStatus } from "@gentle-dot/protocol";+import type { ConnectorsState, DotAction } from "../store.ts";+import "../accounts.css";+import { FlowEvent, FlowPrompt } from "./AccountsPanel.tsx";+import type { Send } from "./types.ts";++interface ConnectorsPanelProps {+ connectors: ConnectorsState;+ send: Send;+ dispatch: (action: DotAction) => void;+ openUrl: (url: string) => void;+}++const STATUS_LABELS: Record<ConnectorStatus, string> = {+ off: "Off",+ needs_signin: "Needs sign-in",+ connected: "Connected",+ error: "Sign-in failed",+};++/** The apps the assistant can use, each signed in from here and set to read only or read and send. */+export function ConnectorsPanel({ connectors, send, dispatch, openUrl }: ConnectorsPanelProps) {+ const flow = connectors.flow;+ const busy = flow !== undefined && flow.done === undefined;+ const name = (id: string) => connectors.list?.find((c) => c.id === id)?.name ?? id;+ const startSignIn = (connector: ConnectorInfo, type: "connector_connect" | "connector_signin") => {+ dispatch({ type: "connector_started", connectorId: connector.id });+ send({ type, connectorId: connector.id });+ };++ return (+ <section className="accounts connectors" aria-label="Connectors">+ <header className="accounts-header">+ <h2>Connectors</h2>+ <button+ type="button"+ className="icon"+ aria-label="Close connectors"+ onClick={() => dispatch({ type: "connectors", open: false })}+ >+ ×+ </button>+ </header>+ <p className="muted">+ Let the assistant use your other apps. It always asks you before it sends or changes anything.+ </p>++ {flow ? (+ <div className="auth-flow">+ <p className="auth-flow-title">Signing in to {name(flow.providerId)}</p>+ {flow.events.map((event, i) => (+ // biome-ignore lint/suspicious/noArrayIndexKey: events are append-only and never reordered+ <FlowEvent key={`${event.kind}-${i}`} event={event} openUrl={openUrl} />+ ))}+ {flow.prompt ? <FlowPrompt key={flow.prompt.message} prompt={flow.prompt} send={send} /> : null}+ {busy && !flow.prompt && flow.events.length === 0 ? <p className="muted">Starting…</p> : null}+ {flow.done ? (+ <p className={`auth-result ${flow.done.ok ? "ok" : "failed"}`} role="status">+ {flow.done.ok+ ? `Connected to ${name(flow.providerId)}.`+ : (flow.done.message ?? "Sign-in did not finish.")}+ </p>+ ) : null}+ <div className="auth-actions">+ {busy && flow.flowId ? (+ <button+ type="button"+ onClick={() => send({ type: "auth_reply", flowId: flow.flowId ?? "", cancelled: true })}+ >+ Cancel+ </button>+ ) : null}+ {flow.done ? (+ <button type="button" onClick={() => dispatch({ type: "connectors", open: true })}>+ Back to connectors+ </button>+ ) : null}+ </div>+ </div>+ ) : (+ <ul className="providers">+ {(connectors.list ?? []).map((connector) => (+ <ConnectorRow+ key={connector.id}+ connector={connector}+ send={send}+ connect={() => startSignIn(connector, "connector_connect")}+ signIn={() => startSignIn(connector, "connector_signin")}+ />+ ))}+ </ul>+ )}+ </section>+ );+}++interface ConnectorRowProps {+ connector: ConnectorInfo;+ send: Send;+ connect: () => void;+ signIn: () => void;+}++function ConnectorRow({ connector: c, send, connect, signIn }: ConnectorRowProps) {+ const nameId = `connector-${c.id}`;+ return (+ <li aria-labelledby={nameId}>+ <div className="provider-name">+ <b id={nameId}>{c.name}</b>+ {c.added ? <span className={`chip connector-${c.status}`}>{STATUS_LABELS[c.status]}</span> : null}+ </div>+ <p className="connector-note">{c.reads}</p>+ <p className="connector-note">+ {c.mode === "read_write" ? c.sends : "It cannot send or change anything."}+ </p>+ {c.enabled ? (+ <fieldset className="connector-mode">+ <legend>What {c.name} may do</legend>+ {(+ [+ ["read_only", "Read only"],+ ["read_write", "Read and send"],+ ] as const+ ).map(([mode, label]) => (+ <label key={mode}>+ <input+ type="radio"+ name={`mode-${c.id}`}+ checked={c.mode === mode}+ onChange={() => send({ type: "connector_mode", connectorId: c.id, mode })}+ />+ {label}+ </label>+ ))}+ </fieldset>+ ) : null}+ <div className="provider-actions">+ {c.enabled ? null : (+ <button type="button" className="primary" aria-label={`Connect ${c.name}`} onClick={connect}>+ Connect+ </button>+ )}+ {c.enabled && c.status !== "connected" ? (+ <button type="button" className="primary" aria-label={`Sign in to ${c.name}`} onClick={signIn}>+ Sign in+ </button>+ ) : null}+ {c.enabled && c.status === "connected" ? (+ <button type="button" aria-label={`Sign in to ${c.name} again`} onClick={signIn}>+ Sign in again+ </button>+ ) : null}+ {c.enabled ? (+ <button+ type="button"+ aria-label={`Disconnect ${c.name}`}+ onClick={() => send({ type: "connector_disconnect", connectorId: c.id })}+ >+ Disconnect+ </button>+ ) : null}+ {c.added ? (+ <button+ type="button"+ className="link"+ aria-label={`Remove ${c.name}`}+ onClick={() => send({ type: "connector_remove", connectorId: c.id })}+ >+ Remove+ </button>+ ) : null}+ </div>+ </li>+ );+}diff --git a/packages/ui/src/components/icons.tsx b/packages/ui/src/components/icons.tsxindex 7da34fa..2826af0 100644--- a/packages/ui/src/components/icons.tsx+++ b/packages/ui/src/components/icons.tsx@@ -42,6 +42,18 @@ export function AccountsIcon() {);}+/** A plug: the apps the assistant can use. */+export function ConnectorsIcon() {+ return (+ <Icon>+ <path d="M9 2v5" />+ <path d="M15 2v5" />+ <path d="M6 7h12v4a6 6 0 0 1-12 0z" />+ <path d="M12 17v5" />+ </Icon>+ );+}+/** Sliders: which model does what. */export function ProfilesIcon() {return (diff --git a/packages/ui/src/store.ts b/packages/ui/src/store.tsindex f3bca2a..c5e46d8 100644--- a/packages/ui/src/store.ts+++ b/packages/ui/src/store.ts@@ -5,6 +5,7 @@ import type {AuthEvent,AuthPrompt,AuthProvider,+ ConnectorInfo,ConversationSummary,Features,MessageQueue,@@ -41,6 +42,14 @@ export interface ProfilesState {lastImport?: { imported: { from: string; to: string }[]; missingProviders: string[] };}+export interface ConnectorsState {+ open: boolean;+ /** Undefined until the first list arrives. */+ list?: ConnectorInfo[];+ /** A connector sign-in; `providerId` is the connector id. */+ flow?: AuthFlowState;+}+export type ConnectionStatus = "connecting" | "open" | "closed" | "unauthorized";export interface ChatMessage {@@ -78,6 +87,7 @@ export interface DotState {notices: Notice[];auth: AuthState;profiles: ProfilesState;+ connectors: ConnectorsState;}export type DotAction =@@ -86,6 +96,8 @@ export type DotAction =| { type: "dismiss"; id: number }| { type: "accounts"; open: boolean }| { type: "profiles"; open: boolean }+ | { type: "connectors"; open: boolean }+ | { type: "connector_started"; connectorId: string }| { type: "auth_started"; providerId: string };export const initialState: DotState = {@@ -101,6 +113,7 @@ export const initialState: DotState = {notices: [],auth: { open: false },profiles: { open: false, roles: [], models: [], importable: false },+ connectors: { open: false },};let nextNotice = 0;@@ -119,12 +132,19 @@ export function reduce(state: DotState, action: DotAction): DotState {// Closing drops the flow; reopening keeps a running one and leaves a finished one.const keep = action.open && state.auth.flow !== undefined && state.auth.flow.done === undefined;return {- ...closeProfiles(state, action.open),+ ...closeConnectors(closeProfiles(state, action.open), action.open),auth: { ...state.auth, open: action.open, flow: keep ? state.auth.flow : undefined },};}case "profiles":- return openProfiles(state, action.open);+ return closeConnectors(openProfiles(state, action.open), action.open);+ case "connectors":+ return openConnectors(state, action.open);+ case "connector_started":+ return {+ ...openConnectors(state, true),+ connectors: { ...state.connectors, open: true, flow: { providerId: action.connectorId, events: [] } },+ };case "auth_started":return {...state,@@ -212,16 +232,20 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {return { ...state, queue: { steering: message.steering, followUp: message.followUp } };case "auth_providers":return {- ...closeProfiles(state, message.open === true),+ ...closeConnectors(closeProfiles(state, message.open === true), message.open === true),auth: { ...state.auth, providers: message.providers, open: message.open ? true : state.auth.open },};+ case "connectors": {+ const updated = { ...state, connectors: { ...state.connectors, list: message.connectors } };+ return message.open ? openConnectors(updated, true) : updated;+ }case "profiles": {const { type: _type, seq: _seq, open, profiles, active, ...rest } = message;const next = { ...state.profiles, ...rest, list: profiles };if (active === undefined) delete next.active;else next.active = active;const updated = { ...state, profiles: next };- return open ? openProfiles(updated, true) : updated;+ return open ? closeConnectors(openProfiles(updated, true), true) : updated;}case "profiles_imported":return {@@ -232,17 +256,28 @@ function reduceServer(state: DotState, message: ServerMessage): DotState {},};case "auth_event":+ if (isConnectorFlow(message.flowId))+ return updateConnectorFlow(state, message.flowId, (f) => ({+ ...f,+ events: [...f.events, message.event],+ }));return updateFlow(state, message.flowId, (f) => ({ ...f, events: [...f.events, message.event] }));case "auth_prompt":+ if (isConnectorFlow(message.prompt.flowId))+ return updateConnectorFlow(state, message.prompt.flowId, (f) => ({ ...f, prompt: message.prompt }));return updateFlow(state, message.prompt.flowId, (f) => ({ ...f, prompt: message.prompt }));- case "auth_done":- return updateFlow(state, message.flowId, (f) => {+ case "auth_done": {+ const finish = (f: AuthFlowState): AuthFlowState => {const { prompt: _prompt, ...rest } = f;return {...rest,done: message.message ? { ok: message.ok, message: message.message } : { ok: message.ok },};- });+ };+ return isConnectorFlow(message.flowId)+ ? updateConnectorFlow(state, message.flowId, finish)+ : updateFlow(state, message.flowId, finish);+ }case "toast":return addNotice(state, message.level, message.message);case "error":@@ -264,6 +299,36 @@ function closeProfiles(state: DotState, when: boolean): DotState {return when && state.profiles.open ? openProfiles(state, false) : state;}+/**+ * Connectors, accounts, and profiles share the screen: opening connectors closes the others.+ * Closing drops the sign-in; reopening keeps a running one and leaves a finished one.+ */+function openConnectors(state: DotState, open: boolean): DotState {+ const flow = state.connectors.flow;+ const keep = open && flow !== undefined && flow.done === undefined;+ const others = open ? openProfiles({ ...state, auth: { ...state.auth, open: false } }, false) : state;+ return { ...others, connectors: { ...state.connectors, open, flow: keep ? flow : undefined } };+}++function closeConnectors(state: DotState, when: boolean): DotState {+ return when && state.connectors.open+ ? { ...state, connectors: { ...state.connectors, open: false } }+ : state;+}++/** Connector sign-ins reuse the sign-in messages, with flow ids of their own. */+const isConnectorFlow = (flowId: string) => flowId.startsWith("connector-");++function updateConnectorFlow(+ state: DotState,+ flowId: string,+ update: (f: AuthFlowState) => AuthFlowState,+): DotState {+ const flow = state.connectors.flow;+ if (!flow || (flow.flowId && flow.flowId !== flowId)) return state;+ return { ...state, connectors: { ...state.connectors, flow: update({ ...flow, flowId }) } };+}+function updateFlow(state: DotState, flowId: string, update: (f: AuthFlowState) => AuthFlowState): DotState {const flow = state.auth.flow;if (!flow || (flow.flowId && flow.flowId !== flowId)) return state;diff --git a/packages/ui/src/styles.css b/packages/ui/src/styles.cssindex ff426f9..1f403a5 100644--- a/packages/ui/src/styles.css+++ b/packages/ui/src/styles.css@@ -835,8 +835,11 @@ textarea:focus {}.ask-message {- margin: 4px 0 0;- color: var(--muted);+ margin: 6px 0 0;+ color: var(--text);+ white-space: pre-wrap;+ overflow-wrap: anywhere;+ line-height: 20px;}.ask-options,diff --git a/packages/ui/test/connectors.test.tsx b/packages/ui/test/connectors.test.tsxnew file mode 100644index 0000000..0197678--- /dev/null+++ b/packages/ui/test/connectors.test.tsx@@ -0,0 +1,249 @@+import { readFileSync } from "node:fs";+import { fileURLToPath } from "node:url";+import type { ClientMessage, ConnectorInfo, ServerMessage, ServerPayload } from "@gentle-dot/protocol";+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { useReducer } from "react";+import { describe, expect, it, vi } from "vitest";+import { AskCard } from "../src/components/AskCard.tsx";+import { ChatSurface } from "../src/components/ChatSurface.tsx";+import { ConnectorsPanel } from "../src/components/ConnectorsPanel.tsx";+import { type DotState, initialState, reduce } from "../src/store.ts";++const connector = (overrides: Partial<ConnectorInfo>): ConnectorInfo => ({+ id: "notion",+ name: "Notion",+ reads: "Search and read your pages.",+ sends: "Create and edit pages, after you approve each one.",+ added: false,+ enabled: false,+ mode: "read_only",+ status: "off",+ ...overrides,+});++const list: ConnectorInfo[] = [+ connector({ added: true, enabled: true, status: "connected" }),+ connector({+ id: "linear",+ name: "Linear",+ added: true,+ enabled: true,+ mode: "read_write",+ status: "needs_signin",+ }),+ connector({ id: "atlassian", name: "Atlassian" }),+];++function apply(state: DotState, ...payloads: ServerPayload[]): DotState {+ return payloads.reduce(+ (s, p) => reduce(s, { type: "server", message: { ...p, seq: 1 } as ServerMessage }),+ state,+ );+}++const ready = apply(+ { ...initialState, connection: "open", agentState: "idle" },+ {+ type: "auth_providers",+ providers: [{ id: "openai", name: "OpenAI", methods: ["api_key"], configured: true }],+ },+);++describe("connectors state", () => {+ it("keeps the list and opens the screen when the server asks (/connectors), closing the others", () => {+ let s = reduce(ready, { type: "accounts", open: true });+ s = apply(s, { type: "connectors", connectors: list });+ expect(s.connectors).toMatchObject({ open: false, list });+ expect(s.auth.open).toBe(true);+ s = apply(s, { type: "connectors", connectors: list, open: true });+ expect(s.connectors.open).toBe(true);+ expect(s.auth.open).toBe(false);+ s = reduce(s, { type: "profiles", open: true });+ expect(s.connectors.open).toBe(false);+ s = reduce(s, { type: "connectors", open: true });+ expect(s.profiles.open).toBe(false);+ expect(s.connectors.open).toBe(true);+ });++ it("tracks a connector sign-in apart from account sign-ins", () => {+ let s = reduce(ready, { type: "auth_started", providerId: "openai" });+ s = reduce(s, { type: "connector_started", connectorId: "notion" });+ expect(s.connectors).toMatchObject({ open: true, flow: { providerId: "notion", events: [] } });+ s = apply(+ s,+ {+ type: "auth_event",+ flowId: "connector-1",+ event: { kind: "auth_url", url: "https://auth.example.com/a" },+ },+ { type: "auth_prompt", prompt: { flowId: "connector-1", kind: "manual_code", message: "Paste it" } },+ );+ expect(s.connectors.flow).toMatchObject({ flowId: "connector-1", prompt: { kind: "manual_code" } });+ expect(s.connectors.flow?.events).toHaveLength(1);+ expect(s.auth.flow).toEqual({ providerId: "openai", events: [] });+ s = apply(s, { type: "auth_done", flowId: "connector-1", providerId: "notion", ok: true });+ expect(s.connectors.flow).toMatchObject({ done: { ok: true } });+ expect(s.connectors.flow?.prompt).toBeUndefined();+ s = reduce(s, { type: "connectors", open: true });+ expect(s.connectors.flow).toBeUndefined();+ });+});++describe("ConnectorsPanel", () => {+ 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} />,+ );+ return { send, dispatch, openUrl };+ }++ it("shows each connector with its status, what it can do, and the actions that apply", async () => {+ const { send, dispatch } = panel(apply(ready, { type: "connectors", connectors: list, open: true }));+ const notion = within(screen.getByRole("listitem", { name: "Notion" }));+ expect(notion.getByText("Connected")).toBeInTheDocument();+ expect(notion.getByText("Search and read your pages.")).toBeInTheDocument();+ expect(notion.getByRole("radio", { name: "Read only" })).toBeChecked();+ const linear = within(screen.getByRole("listitem", { name: "Linear" }));+ expect(linear.getByText("Needs sign-in")).toBeInTheDocument();+ expect(linear.getByText(/after you approve each one/)).toBeInTheDocument();+ expect(linear.getByRole("radio", { name: "Read and send" })).toBeChecked();+ const atlassian = within(screen.getByRole("listitem", { name: "Atlassian" }));+ expect(atlassian.queryByRole("radio")).toBeNull();+ expect(atlassian.queryByRole("button", { name: /Remove/ })).toBeNull();++ const user = userEvent.setup();+ await user.click(notion.getByRole("radio", { name: "Read and send" }));+ await user.click(notion.getByRole("button", { name: "Sign in to Notion again" }));+ await user.click(notion.getByRole("button", { name: "Disconnect Notion" }));+ await user.click(notion.getByRole("button", { name: "Remove Notion" }));+ await user.click(linear.getByRole("button", { name: "Sign in to Linear" }));+ await user.click(atlassian.getByRole("button", { name: "Connect Atlassian" }));+ expect(send.mock.calls.map(([m]) => m)).toEqual([+ { type: "connector_mode", connectorId: "notion", mode: "read_write" },+ { type: "connector_signin", connectorId: "notion" },+ { type: "connector_disconnect", connectorId: "notion" },+ { type: "connector_remove", connectorId: "notion" },+ { type: "connector_signin", connectorId: "linear" },+ { type: "connector_connect", connectorId: "atlassian" },+ ]);+ expect(dispatch.mock.calls.map(([a]) => a)).toEqual([+ { type: "connector_started", connectorId: "notion" },+ { type: "connector_started", connectorId: "linear" },+ { type: "connector_started", connectorId: "atlassian" },+ ]);+ });++ it("offers to turn a connector that is off back on", async () => {+ const off = [connector({ added: true, enabled: false, status: "off" })];+ const { send } = panel(apply(ready, { type: "connectors", connectors: off, open: true }));+ const notion = within(screen.getByRole("listitem", { name: "Notion" }));+ expect(notion.getByText("Off")).toBeInTheDocument();+ expect(notion.queryByRole("button", { name: /Disconnect/ })).toBeNull();+ await userEvent.setup().click(notion.getByRole("button", { name: "Connect Notion" }));+ expect(send).toHaveBeenCalledWith({ type: "connector_connect", connectorId: "notion" });+ });++ it("walks through a sign-in: link, pasted address, cancel, and the result", async () => {+ let s = apply(ready, { type: "connectors", connectors: list, open: true });+ s = reduce(s, { type: "connector_started", connectorId: "linear" });+ s = apply(+ s,+ {+ type: "auth_event",+ flowId: "connector-9",+ event: {+ kind: "auth_url",+ url: "https://auth.example.com/a",+ instructions: "Approve access to Linear.",+ },+ },+ {+ type: "auth_prompt",+ prompt: { flowId: "connector-9", kind: "manual_code", message: "Paste the address" },+ },+ );+ const { send, openUrl } = panel(s);+ expect(screen.getByText("Signing in to Linear")).toBeInTheDocument();+ const user = userEvent.setup();+ await user.click(screen.getByRole("button", { name: "Open the sign-in page" }));+ expect(openUrl).toHaveBeenCalledWith("https://auth.example.com/a");+ await user.type(screen.getByLabelText("Paste the address"), "http://127.0.0.1:1/callback?code=c");+ await user.click(screen.getByRole("button", { name: "Continue" }));+ await user.click(screen.getByRole("button", { name: "Cancel" }));+ expect(send.mock.calls.map(([m]) => m)).toEqual([+ { type: "auth_reply", flowId: "connector-9", value: "http://127.0.0.1:1/callback?code=c" },+ { type: "auth_reply", flowId: "connector-9", cancelled: true },+ ]);+ });++ it("says when a sign-in finished", () => {+ let s = apply(ready, { type: "connectors", connectors: list, open: true });+ s = reduce(s, { type: "connector_started", connectorId: "notion" });+ s = apply(s, { type: "auth_done", flowId: "connector-2", providerId: "notion", ok: true });+ panel(s);+ expect(screen.getByRole("status")).toHaveTextContent("Connected to Notion.");+ expect(screen.getByRole("button", { name: "Back to connectors" })).toBeInTheDocument();+ });+});++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} />;+}++describe("Connectors in the panel", () => {+ it("opens from a header icon with a name and tooltip, and typing closes it", async () => {+ const send = vi.fn();+ render(<Harness initial={apply(ready, { type: "connectors", connectors: list })} send={send} />);+ const button = screen.getByRole("button", { name: "Connectors" });+ expect(button).toHaveAttribute("title", "Connectors");+ expect(button.querySelectorAll("svg")).toHaveLength(1);+ const user = userEvent.setup();+ await user.click(button);+ expect(send).toHaveBeenCalledWith({ type: "connectors_list" });+ expect(screen.getByRole("region", { name: "Connectors" })).toBeInTheDocument();+ await user.type(screen.getByRole("textbox", { name: "Message" }), "h");+ expect(screen.queryByRole("region", { name: "Connectors" })).toBeNull();+ });++ it("keeps a sign-in that waits for a pasted address while the user types", async () => {+ let s = apply(ready, { type: "connectors", connectors: list, open: true });+ s = reduce(s, { type: "connector_started", connectorId: "notion" });+ s = apply(s, {+ type: "auth_prompt",+ prompt: { flowId: "connector-3", kind: "manual_code", message: "Paste" },+ });+ render(<Harness initial={s} send={vi.fn()} />);+ await userEvent.setup().type(screen.getByRole("textbox", { name: "Message" }), "h");+ expect(screen.getByRole("region", { name: "Connectors" })).toBeInTheDocument();+ });+});++describe("approval cards", () => {+ it("keep the preview's line breaks and use legible text", () => {+ render(+ <AskCard+ ask={{+ requestId: "r",+ method: "confirm",+ title: "Allow Notion to create pages?",+ message: "The assistant wants to create pages in Notion.\n\ntitle: Plan\nbody: Hello",+ }}+ send={vi.fn()}+ />,+ );+ const message = screen.getByText(/The assistant wants to create pages/);+ expect(message.textContent).toContain("\ntitle: Plan\nbody: Hello");+ // A variable keeps Vite from turning the address into an asset URL.+ const stylesheet = "../src/styles.css";+ const css = readFileSync(fileURLToPath(new URL(stylesheet, import.meta.url)), "utf8");+ const rule = /\.ask-message \{([^}]*)\}/.exec(css)?.[1] ?? "";+ expect(rule).toMatch(/white-space: pre-wrap/);+ expect(rule).toMatch(/overflow-wrap: anywhere/);+ expect(rule).toMatch(/color: var\(--text\)/);+ });+});