Skip to content

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

TypeScript

feat(daemon): prepare the Discord connector on Windows, and import Claude Desktop and VS Code from AppData

Marcelito35f39a24fd4c
diff --git a/packages/daemon/src/connector-import.ts b/packages/daemon/src/connector-import.ts
index 132d749..c871181 100644
--- a/packages/daemon/src/connector-import.ts
+++ b/packages/daemon/src/connector-import.ts
@@ -1,6 +1,7 @@
/**
* 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 and Linux. Each entry is mapped to
+ * 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
* 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>}`).
@@ -54,6 +55,7 @@ export function scanClientConfigs(home: string): ScannedServer[] {
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",
])
add("Claude Desktop", read(path)?.mcpServers, "literal");
@@ -67,7 +69,11 @@ 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"]) {
+ for (const path of [
+ "Library/Application Support/Code/User/mcp.json",
+ ".config/Code/User/mcp.json",
+ "AppData/Roaming/Code/User/mcp.json",
+ ]) {
const vscode = read(path);
add("VS Code", vscode?.servers, "vscode", vscode?.inputs);
}
diff --git a/packages/daemon/src/connectors.ts b/packages/daemon/src/connectors.ts
index a5499a7..59868bb 100644
--- a/packages/daemon/src/connectors.ts
+++ b/packages/daemon/src/connectors.ts
@@ -1787,6 +1787,8 @@ export interface ConnectorOAuthOptions {
export interface ConnectorManagerOptions {
store: ConnectorStore;
+ /** Prepares the curated Discord runtime before asking for credentials or enabling it. */
+ prepareConnector?: (id: string, signal: AbortSignal) => Promise<void>;
oauth?: ConnectorOAuthOptions;
/** The home folder "Import my MCP servers" scans; default the user's. */
importHome?: string;
@@ -1816,6 +1818,11 @@ export class ConnectorManager {
/** The window that registered the computer helper; it goes away with that window. */
private computerOwner: object | undefined;
private setupFlow: Setup | undefined;
+ private preparation:
+ | { owner: object; id: string; connectorId: string; controller: AbortController }
+ | undefined;
+ private preparationDone: Promise<void> = Promise.resolve();
+ private closed = false;
private readonly failed = new Set<string>();
private readonly waiting = new Map<string, ConnectorDraft>();
private scanned = new Map<string, ScannedServer>();
@@ -1899,46 +1906,83 @@ export class ConnectorManager {
/** Adds or turns on a connector: asks for the values it still needs, then signs in when it has no sign-in yet. */
connect(owner: object, id: string, emit: Emit): ConnectorRefusal | undefined {
+ return this.prepareConfiguration(owner, id, emit, (flowId) =>
+ this.connectPrepared(owner, id, emit, flowId),
+ );
+ }
+
+ private connectPrepared(
+ owner: object,
+ id: string,
+ emit: Emit,
+ flowId?: string,
+ ): ConnectorRefusal | undefined {
const saved = this.options.store.state().connectors[id];
const spec = specOf(id, saved);
if (!spec) return REFUSALS.unknown;
if (this.busy()) return REFUSALS.busy;
if (missingValues(spec, saved?.values)) {
// Nothing is added until every value is there.
- this.askValues(owner, id, spec.fields, emit, (values, flowId) =>
- this.keepValues(
- id,
- values,
- emit,
- flowId,
- (current) => ({ ...current, enabled: true }),
- () => this.afterSetup(owner, id, emit, flowId),
- ),
+ this.askValues(
+ owner,
+ id,
+ spec.fields,
+ emit,
+ (values, flowId) =>
+ this.keepValues(
+ id,
+ values,
+ emit,
+ flowId,
+ (current) => ({ ...current, enabled: true }),
+ () => this.afterSetup(owner, id, emit, flowId),
+ ),
+ flowId,
);
return undefined;
}
this.save(id, (current) => ({ ...current, enabled: true }));
- this.afterSetup(owner, id, emit, `connector-${randomUUID()}`);
+ this.afterSetup(owner, id, emit, flowId ?? `connector-${randomUUID()}`);
return undefined;
}
/** Asks again for the values the user typed (a new token, another OAuth client). */
setup(owner: object, id: string, emit: Emit): ConnectorRefusal | undefined {
+ const saved = this.options.store.state().connectors[id];
+ if (!specOf(id, saved)) return REFUSALS.unknown;
+ if (!saved) return REFUSALS.notAdded;
+ return this.prepareConfiguration(owner, id, emit, (flowId) =>
+ this.setupPrepared(owner, id, emit, flowId),
+ );
+ }
+
+ private setupPrepared(
+ owner: object,
+ id: string,
+ emit: Emit,
+ flowId?: string,
+ ): ConnectorRefusal | undefined {
const saved = this.options.store.state().connectors[id];
const spec = specOf(id, saved);
if (!spec) return REFUSALS.unknown;
if (!saved) return REFUSALS.notAdded;
if (spec.fields.length === 0) return REFUSALS.noSetup;
if (this.busy()) return REFUSALS.busy;
- this.askValues(owner, id, spec.fields, emit, (values, flowId) =>
- this.keepValues(
- id,
- values,
- emit,
- flowId,
- (current) => current,
- () => this.afterSetup(owner, id, emit, flowId),
- ),
+ this.askValues(
+ owner,
+ id,
+ spec.fields,
+ emit,
+ (values, flowId) =>
+ this.keepValues(
+ id,
+ values,
+ emit,
+ flowId,
+ (current) => current,
+ () => this.afterSetup(owner, id, emit, flowId),
+ ),
+ flowId,
);
return undefined;
}
@@ -1956,6 +2000,12 @@ export class ConnectorManager {
/** Answers the flow `owner` started: a typed value, a pasted address, or a cancellation. */
reply(owner: object, flowId: string, answer: { value?: string; cancelled?: boolean }): boolean {
+ const preparation = this.preparation;
+ if (preparation?.id === flowId) {
+ if (preparation.owner !== owner || !answer.cancelled) return false;
+ preparation.controller.abort();
+ return true;
+ }
const setup = this.setupFlow;
if (setup && setup.id === flowId) {
if (setup.owner !== owner) return false;
@@ -1981,17 +2031,27 @@ export class ConnectorManager {
/** A window that goes away takes its sign-in with it. */
cancelOwnedBy(owner: object): void {
+ if (this.preparation?.owner === owner) this.preparation.controller.abort();
if (this.setupFlow?.owner === owner) this.cancelSetup(this.setupFlow);
if (this.flow?.owner === owner) this.cancel(this.flow);
}
+ /** Daemon shutdown must await acquisition exit and staging cleanup, not only request abort. */
+ async close(): Promise<void> {
+ this.closed = true;
+ this.cancelAll();
+ await this.preparationDone;
+ }
+
cancelAll(): void {
+ this.preparation?.controller.abort();
if (this.setupFlow) this.cancelSetup(this.setupFlow);
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 {
+ if (this.preparation?.connectorId === id) this.preparation.controller.abort();
return this.change(id, (saved) => ({ ...saved, enabled: false }));
}
@@ -2001,6 +2061,7 @@ export class ConnectorManager {
/** Forgets the connector and its secrets (its sign-in, tokens, and typed values) in the app's store. */
async remove(id: string): Promise<ConnectorRefusal | undefined> {
+ if (this.preparation?.connectorId === id) this.preparation.controller.abort();
const saved = this.options.store.state().connectors[id];
const spec = specOf(id, saved);
if (!spec) return REFUSALS.unknown;
@@ -2227,7 +2288,63 @@ export class ConnectorManager {
}
private busy(): boolean {
- return this.flow !== undefined || this.setupFlow !== undefined;
+ return (
+ this.closed || this.flow !== undefined || this.setupFlow !== undefined || this.preparation !== undefined
+ );
+ }
+
+ private prepareConfiguration(
+ owner: object,
+ id: string,
+ emit: Emit,
+ proceed: (flowId?: string) => ConnectorRefusal | undefined,
+ ): ConnectorRefusal | undefined {
+ const saved = this.options.store.state().connectors[id];
+ if (!specOf(id, saved)) return REFUSALS.unknown;
+ if (this.busy()) return REFUSALS.busy;
+ const prepare = this.options.prepareConnector;
+ if (!prepare || id !== "discord" || saved?.custom) return proceed();
+ const pending = {
+ owner,
+ id: `connector-setup-${randomUUID()}`,
+ connectorId: id,
+ controller: new AbortController(),
+ };
+ this.preparation = pending;
+ emit({
+ type: "auth_event",
+ flowId: pending.id,
+ event: { kind: "progress", message: "Preparing Discord…" },
+ });
+ this.preparationDone = (async () => {
+ try {
+ await prepare(id, pending.controller.signal);
+ pending.controller.signal.throwIfAborted();
+ this.preparation = undefined;
+ const refused = proceed(pending.id);
+ if (refused)
+ emit({
+ type: "auth_done",
+ flowId: pending.id,
+ providerId: id,
+ ok: false,
+ message: refused.message,
+ });
+ } catch {
+ emit({
+ type: "auth_done",
+ flowId: pending.id,
+ providerId: id,
+ ok: false,
+ message: pending.controller.signal.aborted
+ ? "Preparation cancelled."
+ : "Could not prepare Discord. Try connecting again.",
+ });
+ } finally {
+ if (this.preparation === pending) this.preparation = undefined;
+ }
+ })();
+ return undefined;
}
/** Changes one connector, keeping what is not changed, then has the engine read it again. */
@@ -2283,8 +2400,9 @@ export class ConnectorManager {
fields: readonly SetupField[],
emit: Emit,
finish: (values: Record<string, string>, flowId: string) => void,
+ flowId?: string,
): void {
- const id = `connector-setup-${randomUUID()}`;
+ const id = flowId ?? `connector-setup-${randomUUID()}`;
this.setupFlow = {
id,
connectorId,
diff --git a/packages/daemon/src/daemon.ts b/packages/daemon/src/daemon.ts
index 3595220..8aeabad 100644
--- a/packages/daemon/src/daemon.ts
+++ b/packages/daemon/src/daemon.ts
@@ -24,6 +24,7 @@ import {
ConnectorStore,
policyEnv,
} from "./connectors.ts";
+import { DiscordPackage } from "./discord-package.ts";
import { directAccess, type EngineAccess, engineAccess } from "./engine-access.ts";
import { approvalRequest } from "./extensions/approval-guard.ts";
import {
@@ -228,8 +229,28 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
});
// The engine reaches every connector through the proxy (S25.4); its key changes with every launch.
let port = options.port;
+ const discordPackage =
+ process.platform === "win32" && !options.connectorTransport
+ ? new DiscordPackage(join(options.dataDir, "connector-packages"))
+ : undefined;
const proxy = new McpProxy({
- connector: (id) => connectorStore.proxyView(id),
+ 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." };
+ },
prepare: (id) => connectorStore.prepare(id),
credentials: (id) => connectorStore.credentials(id),
// In the desktop app's native dialog, outside the agent's reach (S25.3).
@@ -311,6 +332,9 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
});
const connectors = new ConnectorManager({
store: connectorStore,
+ ...(discordPackage
+ ? { prepareConnector: (_id: string, signal: AbortSignal) => discordPackage.prepare(signal) }
+ : {}),
...(options.connectorOAuth ? { oauth: options.connectorOAuth } : {}),
...((options.importHome ?? process.env.GENTLE_DOT_IMPORT_HOME)
? { importHome: options.importHome ?? process.env.GENTLE_DOT_IMPORT_HOME }
@@ -425,10 +449,12 @@ export async function startDaemon(options: DaemonOptions): Promise<DotDaemon> {
// Logical refusal and secret invalidation happen NOW, not after native drain.
// Start drain independently so a pending/failed channel cannot skip cleanup.
const channelClosed = attempt(() => app?.close());
+ const preparationClosed = attempt(() => connectors.close());
await attempt(() => {
for (const client of wss.clients) client.terminate();
wss.close();
});
+ await preparationClosed;
await attempt(() => proxy.close());
await attempt(() => serverClosed);
await attempt(() => supervisor.stop());
diff --git a/packages/daemon/src/discord-package.ts b/packages/daemon/src/discord-package.ts
new file mode 100644
index 0000000..bd534c1
--- /dev/null
+++ b/packages/daemon/src/discord-package.ts
@@ -0,0 +1,198 @@
+import { spawn } from "node:child_process";
+import { randomUUID } from "node:crypto";
+import {
+ existsSync,
+ lstatSync,
+ mkdirSync,
+ readdirSync,
+ readFileSync,
+ realpathSync,
+ renameSync,
+ rmSync,
+ writeFileSync,
+} from "node:fs";
+import { createRequire } from "node:module";
+import { dirname, isAbsolute, join, relative, resolve } 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[] };
+type Acquire = (directory: string, signal: AbortSignal) => Promise<void>;
+
+/** Only the curated Discord package; this is not an installer for user-supplied commands. */
+export class DiscordPackage {
+ private readonly ready: string;
+ private readonly root: string;
+ private readonly acquire: Acquire;
+ private active: Promise<void> | undefined;
+ constructor(root: string, acquire: Acquire = acquireDiscord) {
+ this.root = root;
+ this.acquire = acquire;
+ this.ready = join(root, `discord-${VERSION}`);
+ }
+
+ command(): Command | undefined {
+ if (!existsSync(this.ready)) return undefined;
+ try {
+ assertDirectories(this.ready);
+ if (readFileSync(join(this.ready, "ready.json"), "utf8") !== `${VERSION}\n`) return undefined;
+ return validatedCommand(this.ready);
+ } catch {
+ return undefined;
+ }
+ }
+
+ prepare(signal: AbortSignal): Promise<void> {
+ if (this.active) return Promise.reject(new Error("Discord preparation is already running"));
+ const operation = this.install(signal);
+ this.active = operation;
+ void operation
+ .finally(() => {
+ if (this.active === operation) this.active = undefined;
+ })
+ .catch(() => {});
+ return operation;
+ }
+
+ 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);
+ mkdirSync(this.root, { recursive: true, mode: 0o700 });
+ assertDirectories(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");
+ 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));
+ }
+ }
+ const staging = join(this.root, `discord-stage-${process.pid}-${randomUUID()}`);
+ mkdirSync(staging, { mode: 0o700 });
+ try {
+ await this.acquire(staging, signal);
+ signal.throwIfAborted();
+ validatedCommand(staging);
+ if (existsSync(join(staging, "cache"))) removeStaging(join(staging, "cache"));
+ 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.
+ if (!this.command()) throw error;
+ }
+ } finally {
+ if (existsSync(staging)) removeStaging(staging);
+ }
+ }
+}
+
+function assertDirectories(path: string): void {
+ 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;
+ }
+}
+
+function validatedCommand(directory: string): Command {
+ const pkg = join(directory, "node_modules", "@pasympa", "discord-mcp");
+ assertDirectories(pkg);
+ const manifest = join(pkg, "package.json");
+ if (!lstatSync(manifest).isFile() || lstatSync(manifest).isSymbolicLink())
+ throw new Error("Invalid Discord package manifest");
+ const data = JSON.parse(readFileSync(manifest, "utf8"));
+ if (data.name !== "@pasympa/discord-mcp" || data.version !== VERSION)
+ throw new Error("Wrong Discord package version");
+ const bin = typeof data.bin === "string" ? data.bin : data.bin?.["discord-mcp"];
+ 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)
+ throw new Error("Invalid Discord entry point");
+ return { command: process.execPath, args: [entry] };
+}
+
+function removeStaging(directory: string): void {
+ assertDirectories(directory);
+ const inspect = (path: string) => {
+ for (const child of readdirSync(path, { withFileTypes: true })) {
+ if (child.isSymbolicLink()) throw new Error("Refusing linked Discord staging cleanup");
+ if (child.isDirectory()) inspect(join(path, child.name));
+ }
+ };
+ inspect(directory);
+ rmSync(directory, { recursive: true });
+}
+
+function npmCli(): string {
+ const adjacent = join(dirname(process.execPath), "..", "lib", "node_modules", "npm", "bin", "npm-cli.js");
+ if (existsSync(adjacent)) return adjacent;
+ const windows = join(dirname(process.execPath), "node_modules", "npm", "bin", "npm-cli.js");
+ if (existsSync(windows)) return windows;
+ 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> {
+ 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,
+ 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 },
+ );
+ let interrupted = false;
+ const stop = () => {
+ interrupted = true;
+ child.kill();
+ };
+ const timeout = setTimeout(stop, PREPARE_TIMEOUT_MS);
+ signal.addEventListener("abort", stop, { once: true });
+ if (signal.aborted) stop();
+ child.once("error", (error) => {
+ clearTimeout(timeout);
+ signal.removeEventListener("abort", stop);
+ 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();
+ });
+ });
+}
diff --git a/packages/daemon/test/connector-import.test.ts b/packages/daemon/test/connector-import.test.ts
index 59e42af..447e407 100644
--- a/packages/daemon/test/connector-import.test.ts
+++ b/packages/daemon/test/connector-import.test.ts
@@ -182,6 +182,18 @@ describe("scanning other apps' MCP configs", () => {
expect(byName("codegraph")?.server).toEqual({ command: "codegraph", args: ["serve", "--mcp"] });
});
+ it("finds Claude Desktop and VS Code where Windows keeps them (AppData\\Roaming)", () => {
+ const home = tempDir();
+ write(home, "AppData/Roaming/Claude/claude_desktop_config.json", {
+ mcpServers: { files: { command: "npx", args: ["-y", "files-server"] } },
+ });
+ write(home, "AppData/Roaming/Code/User/mcp.json", {
+ servers: { docs: { type: "http", url: "https://docs.example.com/mcp" } },
+ });
+ const found = scanClientConfigs(home).map((server) => `${server.source}:${server.name}`);
+ expect(found).toEqual(["Claude Desktop:files", "VS Code:docs"]);
+ });
+
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-flow.test.ts b/packages/daemon/test/connector-preparation-flow.test.ts
new file mode 100644
index 0000000..f96aadd
--- /dev/null
+++ b/packages/daemon/test/connector-preparation-flow.test.ts
@@ -0,0 +1,130 @@
+import { join } from "node:path";
+import type { ServerPayload } from "@gentle-dot/protocol";
+import { expect, it } from "vitest";
+import { ConnectorManager, ConnectorStore } from "../src/connectors.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
+import { tempDir } from "./helpers.ts";
+
+it("keeps the preparation, credential prompt and completion in the same configuration flow", async () => {
+ const dataDir = tempDir();
+ const store = new ConnectorStore({
+ dataDir,
+ agentHome: join(dataDir, "agent"),
+ secrets: new MemorySecretSource(),
+ });
+ await store.checkIntegrity();
+ const sent: ServerPayload[] = [];
+ const manager = new ConnectorManager({ store, prepareConnector: async () => {} });
+ const owner = {};
+ try {
+ manager.connect(owner, "discord", (m) => sent.push(m));
+ await new Promise<void>((r) => setImmediate(r));
+ const progress = sent.find((m) => m.type === "auth_event");
+ const prompt = sent.find((m) => m.type === "auth_prompt");
+ expect(progress?.type).toBe("auth_event");
+ expect(prompt?.type).toBe("auth_prompt");
+ if (progress?.type !== "auth_event" || prompt?.type !== "auth_prompt")
+ throw new Error("Missing setup events");
+ expect(prompt.prompt.flowId).toBe(progress.flowId);
+ manager.reply(owner, prompt.prompt.flowId, { value: "synthetic-token" });
+ await new Promise<void>((r) => setImmediate(r));
+ expect(sent.find((m) => m.type === "auth_done")).toMatchObject({ flowId: progress.flowId, ok: true });
+ } finally {
+ manager.cancelAll();
+ store.close();
+ }
+});
+
+it("waits for aborted preparation cleanup before manager shutdown completes", async () => {
+ const dataDir = tempDir();
+ const store = new ConnectorStore({
+ dataDir,
+ agentHome: join(dataDir, "agent"),
+ secrets: new MemorySecretSource(),
+ });
+ await store.checkIntegrity();
+ let release!: () => void;
+ let signal!: AbortSignal;
+ let cleaned = false;
+ const sent: ServerPayload[] = [];
+ const manager = new ConnectorManager({
+ store,
+ prepareConnector: async (_id, s) => {
+ signal = s;
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ cleaned = true;
+ },
+ });
+ try {
+ manager.connect({}, "discord", (m) => sent.push(m));
+ let closed = false;
+ const closing = manager.close().then(() => {
+ closed = true;
+ });
+ expect(signal.aborted).toBe(true);
+ await Promise.resolve();
+ expect(closed).toBe(false);
+ expect(cleaned).toBe(false);
+ release();
+ await closing;
+ expect(cleaned).toBe(true);
+ expect(closed).toBe(true);
+ expect(store.state().connectors.discord).toBeUndefined();
+ expect(sent.filter((m) => m.type === "auth_done")).toMatchObject([
+ { ok: false, message: "Preparation cancelled." },
+ ]);
+ expect(sent.some((m) => m.type === "auth_prompt")).toBe(false);
+ } finally {
+ release();
+ manager.cancelAll();
+ store.close();
+ }
+});
+
+it("cancels preparation without asking for credentials, enabling Discord or restarting the engine", async () => {
+ const dataDir = tempDir();
+ const store = new ConnectorStore({
+ dataDir,
+ agentHome: join(dataDir, "agent"),
+ secrets: new MemorySecretSource(),
+ });
+ await store.checkIntegrity();
+ const sent: ServerPayload[] = [];
+ const restarts: boolean[] = [];
+ let release!: () => void;
+ let signal!: AbortSignal;
+ const manager = new ConnectorManager({
+ store,
+ prepareConnector: async (_id, s) => {
+ signal = s;
+ await new Promise<void>((r) => {
+ release = r;
+ });
+ },
+ });
+ const owner = {};
+ manager.onChanged = (restart) => restarts.push(restart);
+ try {
+ manager.connect(owner, "discord", (m) => sent.push(m));
+ const progress = sent.find((m) => m.type === "auth_event");
+ if (progress?.type !== "auth_event") throw new Error("Missing progress");
+ expect(manager.reply({}, progress.flowId, { cancelled: true })).toBe(false);
+ expect(signal.aborted).toBe(false);
+ expect(manager.reply(owner, progress.flowId, { cancelled: true })).toBe(true);
+ expect(signal.aborted).toBe(true);
+ release();
+ await new Promise<void>((r) => setImmediate(r));
+ expect(sent.filter((m) => m.type === "auth_done")).toMatchObject([
+ { ok: false, message: "Preparation cancelled." },
+ ]);
+ expect(sent.some((m) => m.type === "auth_prompt")).toBe(false);
+ expect(store.state().connectors.discord).toBeUndefined();
+ expect(restarts).toEqual([]);
+ } finally {
+ release();
+ manager.cancelAll();
+ store.close();
+ }
+});
diff --git a/packages/daemon/test/connector-preparation.test.ts b/packages/daemon/test/connector-preparation.test.ts
new file mode 100644
index 0000000..ca7cb6d
--- /dev/null
+++ b/packages/daemon/test/connector-preparation.test.ts
@@ -0,0 +1,54 @@
+import { join } from "node:path";
+import type { ServerPayload } from "@gentle-dot/protocol";
+import { expect, it } from "vitest";
+import { ConnectorManager, ConnectorStore } from "../src/connectors.ts";
+import { MemorySecretSource } from "../src/secret-source.ts";
+import { tempDir } from "./helpers.ts";
+
+it("waits for Discord preparation during configuration before enabling or reporting success", async () => {
+ 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 messages: ServerPayload[] = [];
+ const restarts: boolean[] = [];
+ let started = false;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const options = {
+ store,
+ prepareConnector: async (id: string, _signal: AbortSignal) => {
+ expect(id).toBe("discord");
+ started = true;
+ await gate;
+ },
+ };
+ const manager = new ConnectorManager(options);
+ manager.onChanged = (restart) => restarts.push(restart);
+ try {
+ expect(manager.connect({}, "discord", (message) => messages.push(message))).toBeUndefined();
+ await Promise.resolve();
+ expect(started).toBe(true);
+ expect(store.state().connectors.discord?.enabled).not.toBe(true);
+ expect(restarts).not.toContain(true);
+ expect(messages.some((message) => message.type === "auth_done")).toBe(false);
+ expect(
+ messages.some((message) => message.type === "auth_event" && message.event.kind === "progress"),
+ ).toBe(true);
+ release();
+ await new Promise<void>((resolve) => setImmediate(resolve));
+ expect(store.state().connectors.discord?.enabled).toBe(true);
+ expect(restarts.filter(Boolean)).toHaveLength(1);
+ expect(messages.filter((message) => message.type === "auth_done")).toMatchObject([{ ok: true }]);
+ } finally {
+ release();
+ manager.cancelAll();
+ store.close();
+ }
+});
diff --git a/packages/daemon/test/discord-package.test.ts b/packages/daemon/test/discord-package.test.ts
new file mode 100644
index 0000000..77e362a
--- /dev/null
+++ b/packages/daemon/test/discord-package.test.ts
@@ -0,0 +1,98 @@
+import { spawnSync } from "node:child_process";
+import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { expect, it } from "vitest";
+import { DiscordPackage } from "../src/discord-package.ts";
+import { tempDir } from "./helpers.ts";
+
+function installed(folder: string) {
+ const pkg = join(folder, "node_modules", "@pasympa", "discord-mcp");
+ mkdirSync(join(pkg, "dist"), { recursive: true });
+ writeFileSync(
+ join(pkg, "package.json"),
+ JSON.stringify({
+ name: "@pasympa/discord-mcp",
+ version: "2.2.0",
+ bin: { "discord-mcp": "dist/index.js" },
+ }),
+ );
+ writeFileSync(join(pkg, "dist/index.js"), "// synthetic server; never executed\n");
+}
+
+it("publishes a cold preparation only after acquisition and reuses it after owner recreation", async () => {
+ const root = tempDir();
+ let calls = 0;
+ let release!: () => void;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const acquire = async (folder: string) => {
+ calls++;
+ await gate;
+ installed(folder);
+ };
+ const owner = new DiscordPackage(root, acquire);
+ const signal = new AbortController().signal;
+ const pending = owner.prepare(signal);
+ expect(owner.command()).toBeUndefined();
+ release();
+ await pending;
+ expect(calls).toBe(1);
+ const command = owner.command();
+ expect(command?.command).toBe(process.execPath);
+ expect(existsSync(command?.args[0] ?? "")).toBe(true);
+ const reopened = new DiscordPackage(root, async () => {
+ throw new Error("warm start downloaded");
+ });
+ await reopened.prepare(signal);
+ expect(reopened.command()).toEqual(command);
+});
+
+it("does not publish interrupted staging and retries without removing unrelated data", async () => {
+ const root = tempDir();
+ writeFileSync(join(root, "unrelated"), "keep");
+ let calls = 0;
+ const owner = new DiscordPackage(root, async (folder) => {
+ calls++;
+ writeFileSync(join(folder, "partial"), "incomplete");
+ if (calls === 1) throw new Error("download interrupted");
+ installed(folder);
+ });
+ await expect(owner.prepare(new AbortController().signal)).rejects.toThrow("download interrupted");
+ expect(owner.command()).toBeUndefined();
+ expect(readdirSync(root)).toContain("unrelated");
+ await owner.prepare(new AbortController().signal);
+ expect(owner.command()).toBeDefined();
+ expect(calls).toBe(2);
+ expect(existsSync(join(root, "unrelated"))).toBe(true);
+});
+
+it("recovers staging from an exited owner without touching a live owner's staging", async () => {
+ const root = tempDir();
+ const exited = spawnSync(process.execPath, ["-e", "process.exit(0)"]);
+ expect(exited.status).toBe(0);
+ const stale = join(root, `discord-stage-${exited.pid}-00000000-0000-0000-0000-000000000000`);
+ const live = join(root, `discord-stage-${process.pid}-11111111-1111-1111-1111-111111111111`);
+ mkdirSync(stale);
+ writeFileSync(join(stale, "partial"), "interrupted");
+ mkdirSync(live);
+ writeFileSync(join(live, "partial"), "active");
+ const owner = new DiscordPackage(root, async (folder) => {
+ installed(folder);
+ });
+ await owner.prepare(new AbortController().signal);
+ expect(existsSync(stale)).toBe(false);
+ expect(existsSync(join(live, "partial"))).toBe(true);
+ expect(owner.command()).toBeDefined();
+});
+
+it("refuses to publish a cancelled acquisition even if the installer completes", async () => {
+ const root = tempDir();
+ const controller = new AbortController();
+ const owner = new DiscordPackage(root, async (folder) => {
+ installed(folder);
+ controller.abort();
+ });
+ await expect(owner.prepare(controller.signal)).rejects.toThrow();
+ expect(owner.command()).toBeUndefined();
+});
diff --git a/packages/ui/src/components/ConnectorsPanel.tsx b/packages/ui/src/components/ConnectorsPanel.tsx
index 85c0aa5..e9da7e6 100644
--- a/packages/ui/src/components/ConnectorsPanel.tsx
+++ b/packages/ui/src/components/ConnectorsPanel.tsx
@@ -66,7 +66,8 @@ export function ConnectorsPanel({
};
const guided = connectors.list?.find((c) => c.id === guideFor && c.guide);
// Values are asked first; once the sign-in page is on its way, it is a sign-in.
- const settingUp = flow?.flowId?.startsWith("connector-setup-") && flow.events.length === 0;
+ const settingUp =
+ flow?.flowId?.startsWith("connector-setup-") && flow.events.every((event) => event.kind === "progress");
return (
<section className="accounts connectors" aria-label="Connectors">
diff --git a/packages/ui/test/connectors.test.tsx b/packages/ui/test/connectors.test.tsx
index 84e5e95..1e82d61 100644
--- a/packages/ui/test/connectors.test.tsx
+++ b/packages/ui/test/connectors.test.tsx
@@ -114,6 +114,24 @@ describe("ConnectorsPanel", () => {
return { send, dispatch, openUrl };
}
+ it("shows package preparation as setup, not successful connection or sign-in", () => {
+ let state = apply(ready, {
+ type: "connectors",
+ connectors: [connector({ id: "discord", name: "Discord" })],
+ });
+ state = reduce(state, { type: "connector_started", connectorId: "discord" });
+ state = apply(state, {
+ type: "auth_event",
+ flowId: "connector-setup-prepare",
+ event: { kind: "progress", message: "Preparing Discord…" },
+ });
+ panel(state);
+ expect(screen.getByText("Setting up Discord")).toBeInTheDocument();
+ expect(screen.getByText("Preparing Discord…")).toBeInTheDocument();
+ expect(screen.queryByText("Connected to Discord.")).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();
+ });
+
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" }));