A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.
TypeScript
fix(daemon): Discord preparation behind linked folders, through proxies, and visible when pending
Marcelitob0bac7f2da25
diff --git a/packages/daemon/src/connector-import.ts b/packages/daemon/src/connector-import.tsindex c871181..6c880b2 100644--- a/packages/daemon/src/connector-import.ts+++ b/packages/daemon/src/connector-import.ts@@ -1,13 +1,15 @@/*** Finds the MCP servers the user set up in other apps (S20), read-only: Claude Desktop, Claude Code,- * Cursor, VS Code, Windsurf, OpenCode, and Gentle Shell, on macOS, Linux, and Windows (Claude Desktop- * and VS Code keep theirs in `AppData\Roaming` there). Each entry is mapped to+ * Cursor, VS Code, Windsurf, OpenCode, and Gentle Shell, on macOS, Linux, and Windows (VS Code keeps+ * its file in `%APPDATA%` there, and Claude Desktop in `%APPDATA%` or, as the Store/MSIX app, in its+ * package below `%LOCALAPPDATA%\Packages`). Each entry is mapped to* the engine's `mcp.json` schema. Values keep their meaning: a literal stays a literal (escaped, so* the engine neither runs it as `!command` nor expands `$NAME`), an environment reference becomes the* engine's `${NAME}`, and a VS Code input becomes a value the user types in the app (`${input:<id>}`).* The source files are only read; nothing here writes anywhere.*/-import { existsSync, readFileSync, statSync } from "node:fs";+import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";+import { homedir } from "node:os";import { isAbsolute, join } from "node:path";import type { ImportCandidate } from "@gentle-dot/protocol";import { literal, type ServerTemplate, type SetupField } from "./connectors.ts";@@ -34,6 +36,7 @@ const SSE_REASON = "It uses the old SSE transport, which the assistant does notconst NO_SERVER = "It has no command or address the assistant can use.";const MAX_FILE = 50 * 1024 * 1024;const MAX_PROJECTS = 200;+const MAX_PACKAGES = 20;const ENV_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;const INPUT_ID = /^[A-Za-z0-9_.-]{1,64}$/;@@ -41,8 +44,36 @@ type Json = Record<string, unknown>;const isRecord = (value: unknown): value is Json =>typeof value === "object" && value !== null && !Array.isArray(value);+/** Where the scan looks: the home folder and the Windows AppData folders. */+export interface ImportLocations {+ home: string;+ /** `%APPDATA%` (`AppData\Roaming`). */+ appData: string;+ /** `%LOCALAPPDATA%` (`AppData\Local`). */+ localAppData: string;+}++/**+ * The user's own folders, with AppData where Windows says it is (it can be redirected away from the+ * profile); a home given for a test or a fixture keeps everything below it.+ */+export function importLocations(+ importHome: string | undefined,+ env: NodeJS.ProcessEnv = process.env,+ home: string = homedir(),+): ImportLocations {+ const base = importHome ?? home;+ const from = (value: string | undefined, fallback: string) =>+ importHome === undefined && value && isAbsolute(value) ? value : join(base, "AppData", fallback);+ return { home: base, appData: from(env.APPDATA, "Roaming"), localAppData: from(env.LOCALAPPDATA, "Local") };+}+/** Every server in the known configuration files below `home`; files that are missing or broken are skipped. */-export function scanClientConfigs(home: string): ScannedServer[] {+export function scanClientConfigs(+ home: string,+ folders: Partial<Omit<ImportLocations, "home">> = {},+): ScannedServer[] {+ const { appData, localAppData } = { ...importLocations(home), ...folders };const found: ScannedServer[] = [];const read = (path: string) => readJson(join(home, path));const add = (source: string, servers: unknown, syntax: Syntax, inputs?: unknown) => {@@ -52,12 +83,13 @@ export function scanClientConfigs(home: string): ScannedServer[] {if (isRecord(raw)) found.push(mapServer(source, name, raw, { syntax, home, inputs: fields }));};- for (const path of [- "Library/Application Support/Claude/claude_desktop_config.json",- ".config/Claude/claude_desktop_config.json",- "AppData/Roaming/Claude/claude_desktop_config.json",+ for (const file of [+ join(home, "Library/Application Support/Claude/claude_desktop_config.json"),+ join(home, ".config/Claude/claude_desktop_config.json"),+ join(appData, "Claude", "claude_desktop_config.json"),+ ...claudePackages(localAppData),])- add("Claude Desktop", read(path)?.mcpServers, "literal");+ add("Claude Desktop", readJson(file)?.mcpServers, "literal");const claude = read(".claude.json");add("Claude Code", claude?.mcpServers, "claude-code");@@ -69,12 +101,12 @@ export function scanClientConfigs(home: string): ScannedServer[] {}add("Cursor", read(".cursor/mcp.json")?.mcpServers, "vscode");- for (const path of [- "Library/Application Support/Code/User/mcp.json",- ".config/Code/User/mcp.json",- "AppData/Roaming/Code/User/mcp.json",+ for (const file of [+ join(home, "Library/Application Support/Code/User/mcp.json"),+ join(home, ".config/Code/User/mcp.json"),+ join(appData, "Code", "User", "mcp.json"),]) {- const vscode = read(path);+ const vscode = readJson(file);add("VS Code", vscode?.servers, "vscode", vscode?.inputs);}add("Windsurf", read(".codeium/windsurf/mcp_config.json")?.mcpServers, "vscode");@@ -89,6 +121,21 @@ export function scanClientConfigs(home: string): ScannedServer[] {return found;}+/** Claude Desktop installed from the Store (MSIX) keeps its config in its package's virtualized AppData. */+function claudePackages(localAppData: string): string[] {+ try {+ return readdirSync(join(localAppData, "Packages"))+ .filter((name) => name.startsWith("Claude_"))+ .sort()+ .slice(0, MAX_PACKAGES)+ .map((name) =>+ join(localAppData, "Packages", name, "LocalCache", "Roaming", "Claude", "claude_desktop_config.json"),+ );+ } catch {+ return [];+ }+}+function readJson(path: string): Json | undefined {try {if (!existsSync(path) || statSync(path).size > MAX_FILE) return undefined;diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.tsindex 59868bb..d9a5e49 100644--- a/packages/daemon/src/connectors.ts+++ b/packages/daemon/src/connectors.ts@@ -14,7 +14,6 @@ import {writeFileSync,} from "node:fs";import { createRequire } from "node:module";-import { homedir } from "node:os";import { dirname, join } from "node:path";import { fileURLToPath } from "node:url";import type { McpOAuthState } from "@earendil-works/pi-mcp/oauth";@@ -29,7 +28,7 @@ import type {import { MAX_CONNECTOR_DRAFTS } from "@gentle-dot/protocol";import { childGuardFile, childGuardText } from "./child-guard.ts";import { resolveRecord, resolveValue, storedSignIn } from "./connector-credentials.ts";-import { type ScannedServer, scanClientConfigs, valueNotes } from "./connector-import.ts";+import { importLocations, type ScannedServer, scanClientConfigs, valueNotes } from "./connector-import.ts";import {INTEGRITY_KEY_ID,macMatches,@@ -1789,8 +1788,10 @@ export interface ConnectorManagerOptions {store: ConnectorStore;/** Prepares the curated Discord runtime before asking for credentials or enabling it. */prepareConnector?: (id: string, signal: AbortSignal) => Promise<void>;+ /** Whether that runtime is ready; absent where nothing needs preparing. */+ connectorPrepared?: (id: string) => boolean;oauth?: ConnectorOAuthOptions;- /** The home folder "Import my MCP servers" scans; default the user's. */+ /** The home folder "Import my MCP servers" scans; default the user's, with AppData where Windows says. */importHome?: string;log?: (line: string) => void;}@@ -2143,12 +2144,12 @@ export class ConnectorManager {/** Reads the other apps' configurations (only reads them) and lists what it found, without any value. */scan(): ImportCandidate[] {- const home = this.options.importHome ?? homedir();+ const { home, ...folders } = importLocations(this.options.importHome);const groups = new Map<string, { candidate: ImportCandidate; server: ScannedServer }>();const found = new Map<string, ScannedServer>();const computerUrl = this.options.store.computerUrl();const computer = computerUrl === undefined ? undefined : fingerprint({ url: computerUrl });- for (const server of scanClientConfigs(home)) {+ for (const server of scanClientConfigs(home, folders)) {const key = server.server ? fingerprint(server.server) : `${server.source}:${server.name}`;// The helper is built in; a copy of it elsewhere is never offered.if (key === computer) continue;@@ -2282,11 +2283,18 @@ export class ConnectorManager {): ConnectorInfo["status"] {if (!saved?.enabled) return "off";if (missingValues(spec, saved.values)) return "needs_setup";+ if (this.needsPreparation(id, saved)) return "needs_preparation";if (this.failed.has(id)) return "error";if (spec.oauth && !this.options.store.isSignedIn(id)) return "needs_signin";return "connected";}+ /** The curated Discord whose runtime is not on this computer yet (only where it is prepared). */+ private needsPreparation(id: string, saved: SavedConnector | undefined): boolean {+ const prepared = this.options.connectorPrepared;+ return prepared !== undefined && id === "discord" && !saved?.custom && !prepared(id);+ }+private busy(): boolean {return (this.closed || this.flow !== undefined || this.setupFlow !== undefined || this.preparation !== undefined@@ -2304,6 +2312,7 @@ export class ConnectorManager {if (this.busy()) return REFUSALS.busy;const prepare = this.options.prepareConnector;if (!prepare || id !== "discord" || saved?.custom) return proceed();+ if (this.options.connectorPrepared?.(id)) return proceed();const pending = {owner,id: `connector-setup-${randomUUID()}`,@@ -2330,7 +2339,9 @@ export class ConnectorManager {ok: false,message: refused.message,});- } catch {+ } catch (error) {+ if (!pending.controller.signal.aborted)+ this.log(`could not prepare connector ${id}: ${(error as Error).message}`);emit({type: "auth_done",flowId: pending.id,diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.tsindex 8aeabad..d2b4008 100644--- a/packages/daemon/src/daemon.ts+++ b/packages/daemon/src/daemon.ts@@ -25,6 +25,7 @@ import {policyEnv,} from "./connectors.ts";import { DiscordPackage } from "./discord-package.ts";+import { discordProxyView } from "./discord-proxy-view.ts";import { directAccess, type EngineAccess, engineAccess } from "./engine-access.ts";import { approvalRequest } from "./extensions/approval-guard.ts";import {@@ -234,23 +235,12 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {? new DiscordPackage(join(options.dataDir, "connector-packages")): undefined;const proxy = new McpProxy({- connector: (id) => {- const view = connectorStore.proxyView(id);- // A connector that cannot run anyway (no app for its secret) keeps that reason: preparing- // Discord would not help, and its advice would hide the real cause.- if (- !view ||- view.unavailable ||- !discordPackage ||- id !== "discord" ||- connectorStore.state().connectors[id]?.custom- )- return view;- const command = discordPackage.command();- return command- ? { ...view, server: command, revision: `${view.revision}:${command.args[0]}` }- : { ...view, unavailable: "Discord needs preparation. Open Connectors and configure Discord again." };- },+ connector: (id) =>+ discordPackage+ ? discordProxyView(connectorStore.proxyView(id), connectorStore.state().connectors[id], () =>+ discordPackage.command(),+ )+ : connectorStore.proxyView(id),prepare: (id) => connectorStore.prepare(id),credentials: (id) => connectorStore.credentials(id),// In the desktop app's native dialog, outside the agent's reach (S25.3).@@ -333,7 +323,10 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {const connectors = new ConnectorManager({store: connectorStore,...(discordPackage- ? { prepareConnector: (_id: string, signal: AbortSignal) => discordPackage.prepare(signal) }+ ? {+ prepareConnector: (_id: string, signal: AbortSignal) => discordPackage.prepare(signal),+ connectorPrepared: () => discordPackage.command() !== undefined,+ }: {}),...(options.connectorOAuth ? { oauth: options.connectorOAuth } : {}),...((options.importHome ?? process.env.GENTLE_DOT_IMPORT_HOME)diff --git a/packages/daemon/src/discord-package.ts b/packages/daemon/src/discord-package.tsindex bd534c1..62a4a38 100644--- a/packages/daemon/src/discord-package.ts+++ b/packages/daemon/src/discord-package.ts@@ -9,15 +9,21 @@ import {realpathSync,renameSync,rmSync,+ unlinkSync,writeFileSync,} from "node:fs";import { createRequire } from "node:module";-import { dirname, isAbsolute, join, relative, resolve } from "node:path";+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";const VERSION = "2.2.0";const PACKAGE = `@pasympa/discord-mcp@${VERSION}`;const PREPARE_TIMEOUT_MS = 300_000;-type Command = { command: string; args: string[] };+/** What npm needs to run and to reach the registry through a corporate proxy; none of it is a secret. */+const INHERITED =+ /^(path|pathext|systemroot|windir|comspec|temp|tmp|userprofile|localappdata|appdata|home|https?_proxy|no_proxy|node_extra_ca_certs)$/i;+const PROXY = /^https?_proxy$/i;+const MAX_REASON = 600;+export type Command = { command: string; args: string[] };type Acquire = (directory: string, signal: AbortSignal) => Promise<void>;/** Only the curated Discord package; this is not an installer for user-supplied commands. */@@ -26,6 +32,11 @@ export class DiscordPackage {private readonly root: string;private readonly acquire: Acquire;private active: Promise<void> | undefined;+ /**+ * The proxy asks on every lookup; the folder is walked again only after a preparation, or when+ * the entry it validated is gone (the folder was deleted while the daemon runs).+ */+ private cached: { command: Command | undefined } | undefined;constructor(root: string, acquire: Acquire = acquireDiscord) {this.root = root;this.acquire = acquire;@@ -33,11 +44,18 @@ export class DiscordPackage {}command(): Command | undefined {+ const entry = this.cached?.command?.args[0];+ if (entry && !existsSync(entry)) this.cached = undefined;+ this.cached ??= { command: this.validated() };+ return this.cached.command;+ }++ private validated(): Command | undefined {if (!existsSync(this.ready)) return undefined;try {- assertDirectories(this.ready);+ assertDirectories(this.ready, this.root);if (readFileSync(join(this.ready, "ready.json"), "utf8") !== `${VERSION}\n`) return undefined;- return validatedCommand(this.ready);+ return validatedCommand(this.ready, this.root);} catch {return undefined;}@@ -57,54 +75,67 @@ export class DiscordPackage {private async install(signal: AbortSignal): Promise<void> {signal.throwIfAborted();- let ancestor = resolve(this.root);- while (!existsSync(ancestor) && dirname(ancestor) !== ancestor) ancestor = dirname(ancestor);- assertDirectories(ancestor);+ this.cached = undefined;+ // Only this folder and what is below it are checked: the profile or data folder holding it may+ // sit behind a link (macOS /var, a redirected Windows profile, a Dev Drive junction).mkdirSync(this.root, { recursive: true, mode: 0o700 });- assertDirectories(this.root);+ assertDirectories(this.root, this.root);if (this.command()) return;- // An existing published path is not disposable staging: never overwrite it.- if (existsSync(this.ready)) throw new Error("The prepared Discord package needs repair");+ const stagingName = () => join(this.root, `discord-stage-${process.pid}-${randomUUID()}`);+ // A published folder that no longer validates is set aside as staging and prepared again,+ // never repaired in place.+ if (lstatSync(this.ready, { throwIfNoEntry: false })) {+ const aside = stagingName();+ renameSync(this.ready, aside);+ this.cached = undefined;+ discard(aside, this.root);+ }for (const name of readdirSync(this.root)) {const match = /^discord-stage-(\d+)-[0-9a-f-]{36}$/.exec(name);if (!match) continue;try {process.kill(Number(match[1]), 0);} catch (error) {- if ((error as NodeJS.ErrnoException).code === "ESRCH") removeStaging(join(this.root, name));+ if ((error as NodeJS.ErrnoException).code === "ESRCH") discard(join(this.root, name), this.root);}}- const staging = join(this.root, `discord-stage-${process.pid}-${randomUUID()}`);+ const staging = stagingName();mkdirSync(staging, { mode: 0o700 });try {await this.acquire(staging, signal);signal.throwIfAborted();- validatedCommand(staging);- if (existsSync(join(staging, "cache"))) removeStaging(join(staging, "cache"));+ validatedCommand(staging, this.root);+ if (existsSync(join(staging, "cache"))) removeStaging(join(staging, "cache"), this.root);writeFileSync(join(staging, "ready.json"), `${VERSION}\n`, { flag: "wx", mode: 0o600 });try {renameSync(staging, this.ready);} catch (error) {// A concurrent owner may have published the same validated version first.+ this.cached = undefined;if (!this.command()) throw error;}} finally {- if (existsSync(staging)) removeStaging(staging);+ this.cached = undefined;+ // Cleanup that fails must not hide why the preparation failed; a later one retries it.+ if (existsSync(staging)) discard(staging, this.root);}}}-function assertDirectories(path: string): void {+/** Every folder from `path` up to `base` (the packages folder, included) is a real folder, not a link. */+function assertDirectories(path: string, base: string): void {+ const top = resolve(base);for (let current = resolve(path); ; current = dirname(current)) {const stat = lstatSync(current);if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Unsafe Discord package directory");- if (dirname(current) === current) break;+ if (current === top) break;+ if (dirname(current) === current) throw new Error("Unsafe Discord package directory");}}-function validatedCommand(directory: string): Command {+function validatedCommand(directory: string, base: string): Command {const pkg = join(directory, "node_modules", "@pasympa", "discord-mcp");- assertDirectories(pkg);+ assertDirectories(pkg, base);const manifest = join(pkg, "package.json");if (!lstatSync(manifest).isFile() || lstatSync(manifest).isSymbolicLink())throw new Error("Invalid Discord package manifest");@@ -115,15 +146,26 @@ function validatedCommand(directory: string): Command {if (typeof bin !== "string" || isAbsolute(bin)) throw new Error("Invalid Discord entry point");const entry = resolve(pkg, bin);const rel = relative(pkg, entry);- if (rel.startsWith("..") || isAbsolute(rel)) throw new Error("Unconfined Discord entry point");- assertDirectories(dirname(entry));- if (!lstatSync(entry).isFile() || lstatSync(entry).isSymbolicLink() || realpathSync(entry) !== entry)+ if (rel === ".." || rel.startsWith(`..${sep}`) || isAbsolute(rel))+ throw new Error("Unconfined Discord entry point");+ assertDirectories(dirname(entry), base);+ // Compared below the real packages folder, which may itself be reached through a linked ancestor.+ if (+ !lstatSync(entry).isFile() ||+ lstatSync(entry).isSymbolicLink() ||+ relative(realpathSync(base), realpathSync(entry)) !== relative(base, entry)+ )throw new Error("Invalid Discord entry point");return { command: process.execPath, args: [entry] };}-function removeStaging(directory: string): void {- assertDirectories(directory);+/** Removes staging, or a published folder set aside; a link is removed itself, never followed. */+function removeStaging(directory: string, base: string): void {+ if (lstatSync(directory).isSymbolicLink()) {+ unlinkSync(directory);+ return;+ }+ assertDirectories(directory, base);const inspect = (path: string) => {for (const child of readdirSync(path, { withFileTypes: true })) {if (child.isSymbolicLink()) throw new Error("Refusing linked Discord staging cleanup");@@ -134,6 +176,14 @@ function removeStaging(directory: string): void {rmSync(directory, { recursive: true });}+function discard(directory: string, base: string): void {+ try {+ removeStaging(directory, base);+ } catch {+ // Left for a later preparation; it never blocks this one.+ }+}+function npmCli(): string {const adjacent = join(dirname(process.execPath), "..", "lib", "node_modules", "npm", "bin", "npm-cli.js");if (existsSync(adjacent)) return adjacent;@@ -142,57 +192,99 @@ function npmCli(): string {return createRequire(import.meta.url).resolve("npm/bin/npm-cli.js");}-/** Acquisition gets no connector values and no inherited provider credentials. */-async function acquireDiscord(directory: string, signal: AbortSignal): Promise<void> {+/** The installer's environment: no connector values and no inherited provider credentials. */+export function acquisitionEnv(source: NodeJS.ProcessEnv, directory: string): NodeJS.ProcessEnv {const env: NodeJS.ProcessEnv = {};- for (const [key, value] of Object.entries(process.env)) {- if (- /^(path|pathext|systemroot|windir|comspec|temp|tmp|userprofile|localappdata|appdata|home)$/i.test(key)- )- env[key] = value;- }- const userconfig = join(directory, "empty.npmrc");- Object.assign(env, {- npm_config_userconfig: userconfig,+ for (const [key, value] of Object.entries(source)) if (INHERITED.test(key)) env[key] = value;+ const empty = join(directory, "empty.npmrc");+ return {+ ...env,+ npm_config_userconfig: empty,+ npm_config_globalconfig: empty,npm_config_cache: join(directory, "cache"),- });- writeFileSync(userconfig, "", { flag: "wx", mode: 0o600 });- await new Promise<void>((done, fail) => {- const child = spawn(- process.execPath,- [- npmCli(),- "install",- "--prefix",- directory,- "--ignore-scripts",- "--no-audit",- "--no-fund",- "--package-lock=false",- "--bin-links=false",- "--registry=https://registry.npmjs.org",- PACKAGE,- ],- { cwd: directory, env, stdio: "ignore", windowsHide: true },- );+ };+}++async function acquireDiscord(directory: string, signal: AbortSignal): Promise<void> {+ const env = acquisitionEnv(process.env, directory);+ writeFileSync(join(directory, "empty.npmrc"), "", { flag: "wx", mode: 0o600 });+ await runAcquisition(+ [+ npmCli(),+ "install",+ "--prefix",+ directory,+ "--ignore-scripts",+ "--no-audit",+ "--no-fund",+ "--package-lock=false",+ "--bin-links=false",+ "--registry=https://registry.npmjs.org",+ PACKAGE,+ ],+ { cwd: directory, env, signal },+ );+}++/**+ * Runs the installer with Node. When it fails, the error says how it ended and the end of what it+ * printed, without the proxy settings it was given (a proxy address may carry a password).+ */+export function runAcquisition(+ args: string[],+ options: { cwd: string; env: NodeJS.ProcessEnv; signal: AbortSignal; timeoutMs?: number },+): Promise<void> {+ const { cwd, env, signal } = options;+ return new Promise<void>((done, fail) => {+ const child = spawn(process.execPath, args, {+ cwd,+ env,+ stdio: ["ignore", "ignore", "pipe"],+ windowsHide: true,+ });+ let output = "";+ let cut = false;+ child.stderr.setEncoding("utf8");+ child.stderr.on("data", (chunk: string) => {+ output += chunk;+ if (output.length <= 4 * MAX_REASON) return;+ output = output.slice(-4 * MAX_REASON);+ cut = true;+ });let interrupted = false;const stop = () => {interrupted = true;child.kill();};- const timeout = setTimeout(stop, PREPARE_TIMEOUT_MS);+ const timeout = setTimeout(stop, options.timeoutMs ?? PREPARE_TIMEOUT_MS);+ const settle = () => {+ clearTimeout(timeout);+ signal.removeEventListener("abort", stop);+ };signal.addEventListener("abort", stop, { once: true });if (signal.aborted) stop();child.once("error", (error) => {- clearTimeout(timeout);- signal.removeEventListener("abort", stop);+ settle();fail(error);});- child.once("close", (code) => {- clearTimeout(timeout);- signal.removeEventListener("abort", stop);- if (interrupted || code !== 0) fail(new Error("Discord package preparation did not finish"));- else done();+ child.once("close", (code, killed) => {+ settle();+ if (!interrupted && code === 0) return done();+ const ended = interrupted ? "stopped" : killed ? `signal ${killed}` : `exit code ${code}`;+ // What the cut left of its first word (maybe `user:pass@host` without its scheme) is dropped.+ const reason = redacted(cut ? output.replace(/^\S*/, "") : output, env);+ fail(new Error(`Discord package preparation did not finish (${ended})${reason ? `: ${reason}` : ""}`));});});}++function redacted(output: string, env: NodeJS.ProcessEnv): string {+ let text = output;+ for (const [key, value] of Object.entries(env))+ if (PROXY.test(key) && value) text = text.split(value).join("[proxy]");+ return text+ .replace(/(\w+:\/\/)[^\s/@]+@/g, "$1[hidden]@")+ .replace(/\s+/g, " ")+ .trim()+ .slice(-MAX_REASON);+}diff --git a/packages/daemon/src/discord-proxy-view.ts b/packages/daemon/src/discord-proxy-view.tsnew file mode 100644index 0000000..83ca472--- /dev/null+++ b/packages/daemon/src/discord-proxy-view.ts@@ -0,0 +1,24 @@+import type { Command } from "./discord-package.ts";+import type { ProxiedConnector } from "./mcp-proxy.ts";++/** What the agent is told while the package is missing; connecting again prepares it with the saved token. */+export const DISCORD_NEEDS_PREPARATION =+ "Discord needs preparation. Open Connectors and choose Prepare for Discord; its token is kept.";++/**+ * The curated Discord connector as the proxy runs it where it is prepared (Windows): the validated+ * entry with Node instead of an npx shim. `command` is asked only for that connector.+ */+export function discordProxyView(+ view: ProxiedConnector | undefined,+ saved: { custom?: unknown } | undefined,+ command: () => Command | undefined,+): ProxiedConnector | undefined {+ // A connector that cannot run anyway (no app for its secret) keeps that reason: preparing+ // Discord would not help, and its advice would hide the real cause.+ if (!view || view.unavailable || view.id !== "discord" || saved?.custom) return view;+ const prepared = command();+ return prepared+ ? { ...view, server: prepared, revision: `${view.revision}:${prepared.args[0]}` }+ : { ...view, unavailable: DISCORD_NEEDS_PREPARATION };+}diff --git a/packages/daemon/test/connector-import.test.ts b/packages/daemon/test/connector-import.test.tsindex 447e407..eafc3ba 100644--- a/packages/daemon/test/connector-import.test.ts+++ b/packages/daemon/test/connector-import.test.ts@@ -5,7 +5,7 @@ import { mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "nimport { dirname, join } from "node:path";import type { ImportCandidate, ServerPayload } from "@gentle-dot/protocol";import { afterEach, describe, expect, it } from "vitest";-import { scanClientConfigs } from "../src/connector-import.ts";+import { importLocations, scanClientConfigs } from "../src/connector-import.ts";import { ConnectorManager, ConnectorStore } from "../src/connectors.ts";import { MemorySecretSource } from "../src/secret-source.ts";import { tempDir, waitFor } from "./helpers.ts";@@ -194,6 +194,62 @@ describe("scanning other apps' MCP configs", () => {expect(found).toEqual(["Claude Desktop:files", "VS Code:docs"]);});+ it("finds Claude Desktop where its Windows (MSIX) package keeps it, and only Claude's package", () => {+ const home = tempDir();+ const config = "LocalCache/Roaming/Claude/claude_desktop_config.json";+ write(home, `AppData/Local/Packages/Claude_pzs8sxrjxfjjc/${config}`, {+ mcpServers: { files: { command: "npx", args: ["-y", "files-server"] } },+ });+ write(home, `AppData/Local/Packages/ClaudeHelper_123/${config}`, {+ mcpServers: { helper: { command: "helper" } },+ });+ write(home, `AppData/Local/Packages/Other_456/${config}`, {+ mcpServers: { other: { command: "other" } },+ });+ write(home, "AppData/Local/Packages/Claude_broken", "not a folder");+ const found = scanClientConfigs(home).map((server) => `${server.source}:${server.name}`);+ expect(found).toEqual(["Claude Desktop:files"]);+ });++ it("reads AppData where Windows says it is, not below the home folder", () => {+ const home = tempDir();+ const roaming = tempDir();+ const local = tempDir();+ write(home, "AppData/Roaming/Claude/claude_desktop_config.json", {+ mcpServers: { stale: { command: "old" } },+ });+ write(roaming, "Claude/claude_desktop_config.json", { mcpServers: { files: { command: "files" } } });+ write(roaming, "Code/User/mcp.json", {+ servers: { docs: { type: "http", url: "https://docs.example.com/mcp" } },+ });+ write(local, "Packages/Claude_pzs8sxrjxfjjc/LocalCache/Roaming/Claude/claude_desktop_config.json", {+ mcpServers: { notes: { command: "notes" } },+ });+ const found = scanClientConfigs(home, { appData: roaming, localAppData: local }).map(+ (server) => `${server.source}:${server.name}`,+ );+ expect(found).toEqual(["Claude Desktop:files", "Claude Desktop:notes", "VS Code:docs"]);+ });++ it("takes AppData from the environment for the user's home, and from a test home otherwise", () => {+ const roaming = join(tempDir(), "Roaming");+ const local = join(tempDir(), "Local");+ const env = { APPDATA: roaming, LOCALAPPDATA: local };+ const home = tempDir();+ expect(importLocations(undefined, env, home)).toEqual({ home, appData: roaming, localAppData: local });+ const fixture = tempDir();+ expect(importLocations(fixture, env, home)).toEqual({+ home: fixture,+ appData: join(fixture, "AppData", "Roaming"),+ localAppData: join(fixture, "AppData", "Local"),+ });+ expect(importLocations(undefined, { APPDATA: "relative", LOCALAPPDATA: "" }, home)).toEqual({+ home,+ appData: join(home, "AppData", "Roaming"),+ localAppData: join(home, "AppData", "Local"),+ });+ });+it("finds nothing in an empty home and skips files it cannot read", () => {expect(scanClientConfigs(tempDir())).toEqual([]);});diff --git a/packages/daemon/test/connector-preparation.test.ts b/packages/daemon/test/connector-preparation.test.tsindex ca7cb6d..41bc254 100644--- a/packages/daemon/test/connector-preparation.test.ts+++ b/packages/daemon/test/connector-preparation.test.ts@@ -52,3 +52,157 @@ it("waits for Discord preparation during configuration before enabling or reportstore.close();}});++/** Discord connected before preparation existed: its token is kept and it is turned on. */+async function connectedBefore() {+ const dataDir = tempDir();+ const store = new ConnectorStore({+ dataDir,+ agentHome: join(dataDir, "agent"),+ secrets: new MemorySecretSource(),+ });+ await store.checkIntegrity();+ await store.keepValues("discord", { token: "synthetic-discord-token" });+ const earlier = new ConnectorManager({ store });+ earlier.connect({}, "discord", () => {});+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(store.state().connectors.discord?.enabled).toBe(true);+ return store;+}++it("lists an enabled Discord that is not prepared as needing preparation, and only Discord", async () => {+ const store = await connectedBefore();+ try {+ let prepared = false;+ const asked = new Set<string>();+ const manager = new ConnectorManager({+ store,+ prepareConnector: async () => {},+ connectorPrepared: (id) => {+ asked.add(id);+ return prepared;+ },+ });+ const status = (id: string) => manager.list().find((c) => c.id === id)?.status;+ expect(status("discord")).toBe("needs_preparation");+ expect(manager.list().filter((c) => c.status === "needs_preparation")).toHaveLength(1);+ expect([...asked]).toEqual(["discord"]);+ prepared = true;+ expect(status("discord")).toBe("connected");+ // Where nothing is prepared (macOS, Linux), the connector runs as before.+ expect(new ConnectorManager({ store }).list().find((c) => c.id === "discord")?.status).toBe("connected");+ manager.disconnect("discord");+ prepared = false;+ expect(status("discord")).toBe("off");+ } finally {+ store.close();+ }+});++it("prepares an enabled Discord on connect with the token it already has", async () => {+ const store = await connectedBefore();+ const sent: ServerPayload[] = [];+ let prepared = false;+ let calls = 0;+ const manager = new ConnectorManager({+ store,+ prepareConnector: async () => {+ calls++;+ prepared = true;+ },+ connectorPrepared: () => prepared,+ });+ try {+ expect(manager.connect({}, "discord", (m) => sent.push(m))).toBeUndefined();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(calls).toBe(1);+ expect(sent.some((m) => m.type === "auth_prompt")).toBe(false);+ expect(sent.filter((m) => m.type === "auth_done")).toMatchObject([{ ok: true }]);+ expect(manager.list().find((c) => c.id === "discord")?.status).toBe("connected");+ expect(await store.credentials("discord")).toMatchObject({+ env: { DISCORD_TOKEN: "synthetic-discord-token" },+ });+ } finally {+ manager.cancelAll();+ store.close();+ }+});++it("does not prepare or say it is preparing when Discord is already prepared", async () => {+ const store = await connectedBefore();+ const sent: ServerPayload[] = [];+ let calls = 0;+ const manager = new ConnectorManager({+ store,+ prepareConnector: async () => {+ calls++;+ },+ connectorPrepared: () => true,+ });+ try {+ manager.setup({}, "discord", (m) => sent.push(m));+ expect(calls).toBe(0);+ expect(sent.some((m) => m.type === "auth_event")).toBe(false);+ expect(sent.find((m) => m.type === "auth_prompt")).toBeDefined();+ } finally {+ manager.cancelAll();+ store.close();+ }+});++it("logs nothing when a preparation is cancelled", async () => {+ const store = await connectedBefore();+ const logs: string[] = [];+ const sent: ServerPayload[] = [];+ const manager = new ConnectorManager({+ store,+ prepareConnector: (_id, signal) =>+ new Promise<void>((_resolve, reject) => {+ signal.addEventListener("abort", () =>+ reject(new Error("Discord package preparation did not finish (stopped)")),+ );+ }),+ connectorPrepared: () => false,+ log: (line) => logs.push(line),+ });+ try {+ manager.connect({}, "discord", (m) => sent.push(m));+ await Promise.resolve();+ manager.cancelAll();+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(sent.filter((m) => m.type === "auth_done")).toMatchObject([+ { ok: false, message: "Preparation cancelled." },+ ]);+ expect(logs.some((line) => line.includes("could not prepare connector discord"))).toBe(false);+ } finally {+ manager.cancelAll();+ store.close();+ }+});++it("logs why a preparation failed", async () => {+ const store = await connectedBefore();+ const logs: string[] = [];+ const sent: ServerPayload[] = [];+ const manager = new ConnectorManager({+ store,+ prepareConnector: async () => {+ throw new Error("Discord package preparation did not finish (exit code 1): npm error code E404");+ },+ connectorPrepared: () => false,+ log: (line) => logs.push(line),+ });+ try {+ manager.connect({}, "discord", (m) => sent.push(m));+ await new Promise<void>((resolve) => setImmediate(resolve));+ expect(logs).toContain(+ "could not prepare connector discord: Discord package preparation did not finish (exit code 1): npm error code E404",+ );+ expect(sent.filter((m) => m.type === "auth_done")).toMatchObject([+ { ok: false, message: "Could not prepare Discord. Try connecting again." },+ ]);+ } finally {+ manager.cancelAll();+ store.close();+ }+});diff --git a/packages/daemon/test/discord-package.test.ts b/packages/daemon/test/discord-package.test.tsindex 77e362a..9b1fbc2 100644--- a/packages/daemon/test/discord-package.test.ts+++ b/packages/daemon/test/discord-package.test.ts@@ -1,11 +1,26 @@import { spawnSync } from "node:child_process";-import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";+import {+ existsSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ renameSync,+ rmSync,+ symlinkSync,+ unlinkSync,+ writeFileSync,+} from "node:fs";import { join } from "node:path";import { expect, it } from "vitest";-import { DiscordPackage } from "../src/discord-package.ts";+import { acquisitionEnv, DiscordPackage, runAcquisition } from "../src/discord-package.ts";import { tempDir } from "./helpers.ts";-function installed(folder: string) {+// Directory links: a junction on Windows needs no privilege; file links are skipped there.+const linkDir = (target: string, path: string) =>+ symlinkSync(target, path, process.platform === "win32" ? "junction" : "dir");+const noFileLinks = process.platform === "win32";++function installed(folder: string, manifest: Record<string, unknown> = {}) {const pkg = join(folder, "node_modules", "@pasympa", "discord-mcp");mkdirSync(join(pkg, "dist"), { recursive: true });writeFileSync(@@ -14,11 +29,23 @@ function installed(folder: string) {name: "@pasympa/discord-mcp",version: "2.2.0",bin: { "discord-mcp": "dist/index.js" },+ ...manifest,}),);writeFileSync(join(pkg, "dist/index.js"), "// synthetic server; never executed\n");}+/** A published folder as a previous preparation left it, then changed by `damage`. */+function published(root: string, damage: (ready: string, pkg: string) => void = () => {}) {+ const ready = join(root, "discord-2.2.0");+ installed(ready);+ writeFileSync(join(ready, "ready.json"), "2.2.0\n");+ damage(ready, join(ready, "node_modules", "@pasympa", "discord-mcp"));+ return ready;+}++const packagesRoot = () => join(tempDir(), "connector-packages");+it("publishes a cold preparation only after acquisition and reuses it after owner recreation", async () => {const root = tempDir();let calls = 0;@@ -96,3 +123,238 @@ it("refuses to publish a cancelled acquisition even if the installer completes",await expect(owner.prepare(controller.signal)).rejects.toThrow();expect(owner.command()).toBeUndefined();});++it("prepares when the data folder sits behind a linked ancestor (macOS /var, a Windows junction)", async () => {+ const real = tempDir();+ const linked = join(tempDir(), "linked-profile");+ linkDir(real, linked);+ const root = join(linked, "data", "connector-packages");+ const owner = new DiscordPackage(root, async (folder) => installed(folder));+ await owner.prepare(new AbortController().signal);+ expect(owner.command()?.command).toBe(process.execPath);+ expect(new DiscordPackage(root).command()).toEqual(owner.command());+});++it("still refuses a linked connector-packages folder", async () => {+ const parent = tempDir();+ const elsewhere = tempDir();+ const root = join(parent, "connector-packages");+ linkDir(elsewhere, root);+ let calls = 0;+ const owner = new DiscordPackage(root, async (folder) => {+ calls++;+ installed(folder);+ });+ await expect(owner.prepare(new AbortController().signal)).rejects.toThrow(+ "Unsafe Discord package directory",+ );+ expect(calls).toBe(0);+ expect(readdirSync(elsewhere)).toEqual([]);+});++it("prepares again over a published folder that no longer validates, instead of dead-ending", async () => {+ const root = packagesRoot();+ const ready = published(root, (_ready, pkg) => rmSync(join(pkg, "dist", "index.js")));+ writeFileSync(join(root, "unrelated"), "keep");+ let calls = 0;+ const owner = new DiscordPackage(root, async (folder) => {+ calls++;+ installed(folder);+ });+ expect(owner.command()).toBeUndefined();+ await owner.prepare(new AbortController().signal);+ expect(calls).toBe(1);+ expect(owner.command()?.args).toEqual([+ join(ready, "node_modules", "@pasympa", "discord-mcp", "dist", "index.js"),+ ]);+ expect(readdirSync(root).sort()).toEqual(["discord-2.2.0", "unrelated"]);+});++it("sets a linked published folder aside without following it", async () => {+ const root = packagesRoot();+ mkdirSync(root, { recursive: true });+ const outside = tempDir();+ writeFileSync(join(outside, "keep"), "outside");+ linkDir(outside, join(root, "discord-2.2.0"));+ const owner = new DiscordPackage(root, async (folder) => installed(folder));+ await owner.prepare(new AbortController().signal);+ expect(owner.command()).toBeDefined();+ expect(readFileSync(join(outside, "keep"), "utf8")).toBe("outside");+});++it("keeps answering from what it validated until a preparation publishes", async () => {+ const root = packagesRoot();+ published(root);+ const owner = new DiscordPackage(root);+ const command = owner.command();+ expect(command).toBeDefined();+ // Proxy lookups do not walk the folder again while the entry is still there.+ unlinkSync(join(root, "discord-2.2.0", "ready.json"));+ expect(owner.command()).toEqual(command);+ expect(new DiscordPackage(root).command()).toBeUndefined();+ writeFileSync(join(root, "discord-2.2.0", "ready.json"), "2.2.0\n");+ renameSync(join(root, "discord-2.2.0"), join(root, "moved"));+ const fresh = new DiscordPackage(root, async (folder) => installed(folder));+ expect(fresh.command()).toBeUndefined();+ await fresh.prepare(new AbortController().signal);+ expect(fresh.command()).toEqual(command);+});++it("stops answering once the prepared folder is deleted, so it is prepared again", async () => {+ const root = packagesRoot();+ const ready = published(root);+ let calls = 0;+ const owner = new DiscordPackage(root, async (folder) => {+ calls++;+ installed(folder);+ });+ const command = owner.command();+ expect(command).toBeDefined();+ rmSync(ready, { recursive: true });+ expect(owner.command()).toBeUndefined();+ await owner.prepare(new AbortController().signal);+ expect(calls).toBe(1);+ expect(owner.command()).toEqual(command);+});++const rejections: [string, (ready: string, pkg: string) => void, boolean?][] = [+ ["no ready.json", (ready) => unlinkSync(join(ready, "ready.json"))],+ ["a ready.json for another version", (ready) => writeFileSync(join(ready, "ready.json"), "2.1.0\n")],+ ["another version", (_r, pkg) => installed(join(pkg, "..", "..", ".."), { version: "2.1.0" })],+ ["another package name", (_r, pkg) => installed(join(pkg, "..", "..", ".."), { name: "discord-mcp" })],+ ["no manifest", (_r, pkg) => unlinkSync(join(pkg, "package.json"))],+ ["no bin", (_r, pkg) => installed(join(pkg, "..", "..", ".."), { bin: {} })],+ [+ "an absolute bin",+ (_r, pkg) => installed(join(pkg, "..", "..", ".."), { bin: join(pkg, "dist", "index.js") }),+ ],+ ["a bin outside the package", (_r, pkg) => installed(join(pkg, "..", "..", ".."), { bin: "../escape.js" })],+ ["a missing entry", (_r, pkg) => unlinkSync(join(pkg, "dist", "index.js"))],+ ["an entry that is a folder", (_r, pkg) => installed(join(pkg, "..", "..", ".."), { bin: "dist" })],+ [+ "a linked package folder",+ (ready, pkg) => {+ renameSync(pkg, join(ready, "real-package"));+ linkDir(join(ready, "real-package"), pkg);+ },+ ],+ [+ "a linked entry folder",+ (_r, pkg) => {+ renameSync(join(pkg, "dist"), join(pkg, "real-dist"));+ linkDir(join(pkg, "real-dist"), join(pkg, "dist"));+ },+ ],+ [+ "a linked entry",+ (_r, pkg) => {+ renameSync(join(pkg, "dist", "index.js"), join(pkg, "dist", "real.js"));+ symlinkSync(join(pkg, "dist", "real.js"), join(pkg, "dist", "index.js"));+ },+ true,+ ],+ [+ "a linked manifest",+ (_r, pkg) => {+ renameSync(join(pkg, "package.json"), join(pkg, "real.json"));+ symlinkSync(join(pkg, "real.json"), join(pkg, "package.json"));+ },+ true,+ ],+];++for (const [name, damage, fileLink] of rejections)+ it.skipIf(fileLink && noFileLinks)(`does not run a published package with ${name}`, () => {+ const root = packagesRoot();+ published(root, damage);+ expect(new DiscordPackage(root).command()).toBeUndefined();+ });++it("accepts an entry whose name only starts with two dots", () => {+ const root = packagesRoot();+ published(root, (_r, pkg) => {+ mkdirSync(join(pkg, "..dist"));+ writeFileSync(join(pkg, "..dist", "index.js"), "// synthetic\n");+ installed(join(pkg, "..", "..", ".."), { bin: "..dist/index.js" });+ });+ expect(new DiscordPackage(root).command()?.args[0]).toMatch(/\.\.dist[\\/]index\.js$/);+});++it("refuses to publish an acquisition that does not validate", async () => {+ const root = packagesRoot();+ const owner = new DiscordPackage(root, async (folder) => installed(folder, { version: "2.1.0" }));+ await expect(owner.prepare(new AbortController().signal)).rejects.toThrow("Wrong Discord package version");+ expect(owner.command()).toBeUndefined();+ expect(readdirSync(root)).toEqual([]);+});++it("gives npm the proxy and CA settings it reads, and nothing else from the environment", () => {+ const env = acquisitionEnv(+ {+ PATH: "/usr/bin",+ HTTPS_PROXY: "http://proxy.example:8080",+ https_proxy: "http://lower.example:8080",+ HTTP_PROXY: "http://plain.example:8080",+ http_proxy: "http://plain-lower.example:8080",+ NO_PROXY: "localhost",+ no_proxy: ".internal",+ NODE_EXTRA_CA_CERTS: "/etc/corp-ca.pem",+ DISCORD_TOKEN: "synthetic-discord-token",+ ANTHROPIC_API_KEY: "synthetic-key",+ NODE_OPTIONS: "--require /tmp/x.js",+ npm_config_registry: "https://evil.example",+ },+ "/stage",+ );+ expect(env).toEqual({+ PATH: "/usr/bin",+ HTTPS_PROXY: "http://proxy.example:8080",+ https_proxy: "http://lower.example:8080",+ HTTP_PROXY: "http://plain.example:8080",+ http_proxy: "http://plain-lower.example:8080",+ NO_PROXY: "localhost",+ no_proxy: ".internal",+ NODE_EXTRA_CA_CERTS: "/etc/corp-ca.pem",+ npm_config_userconfig: join("/stage", "empty.npmrc"),+ npm_config_globalconfig: join("/stage", "empty.npmrc"),+ npm_config_cache: join("/stage", "cache"),+ });+});++it("says why the installer failed without repeating proxy credentials", async () => {+ const folder = tempDir();+ const script =+ "process.stderr.write('npm error request to https://registry.npmjs.org failed via http://user:[email protected]\\nnpm error code E404\\n'); process.exit(3)";+ const failure = runAcquisition(["-e", script], {+ cwd: folder,+ env: { PATH: process.env.PATH, HTTPS_PROXY: "http://user:[email protected]" },+ signal: new AbortController().signal,+ });+ await expect(failure).rejects.toThrow(/exit code 3.*E404/s);+ await failure.catch((error: Error) => expect(error.message).not.toContain("hunter2"));+});++it("hides credentials in an address it was not given", async () => {+ const script =+ "process.stderr.write('npm error request failed via https://bob:[email protected]:3128/x\\n'); process.exit(1)";+ const failure = runAcquisition(["-e", script], {+ cwd: tempDir(),+ env: { PATH: process.env.PATH },+ signal: new AbortController().signal,+ });+ await expect(failure).rejects.toThrow("https://[hidden]@other-proxy.example:3128/x");+ await failure.catch((error: Error) => expect(error.message).not.toMatch(/bob|s3cret/));+});++it("hides credentials whose address was cut where the kept output starts", async () => {+ // Kept output is the last 2400 characters; the cut lands inside the user name.+ const tail = `er:[email protected] ${"\n".repeat(2400 - 24)}`;+ const script = `process.stderr.write('npm error via http://us' + ${JSON.stringify(tail)}); process.exit(1)`;+ const failure = runAcquisition(["-e", script], {+ cwd: tempDir(),+ env: { PATH: process.env.PATH },+ signal: new AbortController().signal,+ });+ await expect(failure).rejects.toThrow("exit code 1");+ await failure.catch((error: Error) => expect(error.message).not.toContain("s3cret"));+});diff --git a/packages/daemon/test/discord-proxy-view.test.ts b/packages/daemon/test/discord-proxy-view.test.tsnew file mode 100644index 0000000..e9be278--- /dev/null+++ b/packages/daemon/test/discord-proxy-view.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";+import { DISCORD_NEEDS_PREPARATION, discordProxyView } from "../src/discord-proxy-view.ts";+import type { ProxiedConnector } from "../src/mcp-proxy.ts";++const view = (overrides: Partial<ProxiedConnector> = {}): ProxiedConnector => ({+ id: "discord",+ name: "Discord",+ enabled: true,+ mode: "read_only",+ readOnlyTools: ["read_messages"],+ server: { command: "npx", args: ["-y", "@pasympa/[email protected]"] },+ revision: "abc",+ ...overrides,+});+const entry = "/data/connector-packages/discord-2.2.0/node_modules/@pasympa/discord-mcp/dist/index.js";+const prepared = () => ({ command: "/opt/node/bin/node", args: [entry] });+const never = () => {+ throw new Error("the package was looked up");+};++describe("the Discord connector as the proxy runs it where it is prepared", () => {+ it("runs the prepared entry with Node and makes a new connection when the entry changes", () => {+ expect(discordProxyView(view(), {}, prepared)).toEqual(+ view({ server: { command: "/opt/node/bin/node", args: [entry] }, revision: `abc:${entry}` }),+ );+ });++ it("says it needs preparation while the package is not there", () => {+ expect(discordProxyView(view(), {}, () => undefined)).toEqual(+ view({ unavailable: DISCORD_NEEDS_PREPARATION }),+ );+ expect(DISCORD_NEEDS_PREPARATION).not.toMatch(/configure/i);+ });++ it("keeps the reason it already has (a secret it cannot read) without looking at the package", () => {+ const locked = view({ unavailable: "The desktop app is not connected." });+ expect(discordProxyView(locked, {}, never)).toBe(locked);+ });++ it("leaves a server of the user's own named discord, other connectors and missing ones alone", () => {+ const custom = view();+ expect(discordProxyView(custom, { custom: { server: { command: "discord" } } }, never)).toBe(custom);+ const slack = view({ id: "slack", name: "Slack", server: { url: "https://mcp.slack.com/mcp" } });+ expect(discordProxyView(slack, {}, never)).toBe(slack);+ expect(discordProxyView(undefined, undefined, never)).toBeUndefined();+ });+});diff --git a/packages/protocol/src/index.ts b/packages/protocol/src/index.tsindex 48f96b6..25bc263 100644--- a/packages/protocol/src/index.ts+++ b/packages/protocol/src/index.ts@@ -150,8 +150,18 @@ export type AuthEvent =/** 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; `needs_setup`: a value the user types is missing; `error`: the last sign-in failed. */-export type ConnectorStatus = "off" | "needs_setup" | "needs_signin" | "connected" | "error";+/**+ * `off`: not added or turned off; `needs_setup`: a value the user types is missing; `needs_preparation`:+ * what it runs is not on this computer yet (Discord on Windows), and connecting again prepares it with+ * the values it already has; `error`: the last sign-in failed.+ */+export type ConnectorStatus =+ | "off"+ | "needs_setup"+ | "needs_preparation"+ | "needs_signin"+ | "connected"+ | "error";/** In-app steps for a connector the user sets up with an app or bot of their own. */export interface ConnectorGuide {diff --git a/packages/ui/src/accounts.css b/packages/ui/src/accounts.cssindex b14b1ae..25ef732 100644--- a/packages/ui/src/accounts.css+++ b/packages/ui/src/accounts.css@@ -121,7 +121,8 @@ button.back {color: var(--green);}-.chip.connector-needs_setup {+.chip.connector-needs_setup,+.chip.connector-needs_preparation {color: var(--yellow);border-color: rgba(224, 194, 122, 0.45);}diff --git a/packages/ui/src/components/ConnectorsPanel.tsx b/packages/ui/src/components/ConnectorsPanel.tsxindex e9da7e6..2a3793a 100644--- a/packages/ui/src/components/ConnectorsPanel.tsx+++ b/packages/ui/src/components/ConnectorsPanel.tsx@@ -31,6 +31,7 @@ interface ConnectorsPanelProps {const STATUS_LABELS: Record<ConnectorStatus, string> = {off: "Off",needs_setup: "Needs setup",+ needs_preparation: "Needs preparation",needs_signin: "Needs sign-in",connected: "Connected",error: "Sign-in failed",@@ -380,7 +381,8 @@ function ConnectorRow({ connector: c, appSend, connect, signIn, setUp }: Connectconst readOnlyNote = c.custom? "Its tools stay hidden until you choose Read and send. Then it asks you before every action.": "It cannot send or change anything.";- const canSignIn = c.enabled && !c.noSignIn && c.status !== "needs_setup";+ const canSignIn =+ c.enabled && !c.noSignIn && c.status !== "needs_setup" && c.status !== "needs_preparation";return (<li aria-labelledby={nameId}><div className="provider-name">@@ -440,6 +442,18 @@ function ConnectorRow({ connector: c, appSend, connect, signIn, setUp }: ConnectSet up</button>) : null}+ {c.enabled && c.status === "needs_preparation" ? (+ // Connecting again prepares what it runs and keeps the values it already has.+ <button+ type="button"+ className="primary"+ aria-label={`Prepare ${c.name}`}+ disabled={locked}+ onClick={connect}+ >+ Prepare+ </button>+ ) : null}{canSignIn && c.status !== "connected" ? (<buttontype="button"diff --git a/packages/ui/test/connectors.test.tsx b/packages/ui/test/connectors.test.tsxindex 1e82d61..41ef569 100644--- a/packages/ui/test/connectors.test.tsx+++ b/packages/ui/test/connectors.test.tsx@@ -114,6 +114,31 @@ describe("ConnectorsPanel", () => {return { send, dispatch, openUrl };}+ it("shows a Discord connected before preparation as needing it, and prepares it with Connect again", async () => {+ const { send } = panel(+ apply(ready, {+ type: "connectors",+ connectors: [+ connector({+ id: "discord",+ name: "Discord",+ added: true,+ enabled: true,+ status: "needs_preparation",+ noSignIn: true,+ }),+ ],+ open: true,+ }),+ );+ const discord = within(screen.getByRole("listitem", { name: "Discord" }));+ expect(discord.getByText("Needs preparation")).toBeInTheDocument();+ expect(discord.queryByText("Connected")).not.toBeInTheDocument();+ expect(discord.queryByRole("button", { name: "Set up Discord" })).not.toBeInTheDocument();+ await userEvent.setup().click(discord.getByRole("button", { name: "Prepare Discord" }));+ expect(send).toHaveBeenCalledWith({ type: "connector_connect", connectorId: "discord" });+ });+it("shows package preparation as setup, not successful connection or sign-in", () => {let state = apply(ready, {type: "connectors",