Files
Netcatty/electron/bridges/aiBridge/agentAuthProbes.cjs
T
陈大猫andClaude Opus 5.5 2318434ac9 perf(ai): stop freezing the app during agent discovery and chat backups (#4116)
Both paths ran synchronous I/O on the Electron main process, which freezes
every window and the terminal keystroke relay while it runs:

- Agent discovery (opening the AI panel or Settings > AI) probed auth with
  execFileSync: `security find-generic-password` (4 s timeout), `gh auth
  status` (network, 5 s), `which cursor-agent` (4 s) and `cursor-agent status`
  (8 s), one after another. The probes now use a non-rejecting async execFile
  helper with the same result shape; discovery awaits them.
- Cursor SDK detection evaluated `import("@cursor/sdk")` (~4 MB of ESM plus
  its transport stack) only to check that it is installed, and kept it
  resident afterwards. It now checks for the ESM entry that the dynamic import
  loads; the SDK itself still loads on first use. The package does not export
  package.json and its CJS build is stripped from releases, so the check walks
  require.resolve.paths() instead of using require.resolve.
- The AI chat backup wrote the whole history (often several MB) with
  writeFileSync on every debounced change. Writes now use fs.promises and are
  serialized so generations cannot interleave.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 00:21:50 -08:00

299 lines
11 KiB
JavaScript

"use strict";
/**
* Layer-3 (authentication) CLI probes for the managed backends.
* Each probe is dependency-injected (runners / fileExists) for unit testing;
* the discovery handler wires the real implementations.
*
* Returns: { authenticated: boolean, authSource: string|null }
*/
const { existsSync, readFileSync } = require("node:fs");
const os = require("node:os");
const path = require("node:path");
const { execFile } = require("node:child_process");
const { resolveCursorCliSpawnSpec } = require("./cursorCliSpawn.cjs");
function defaultFileExists(p) {
try { return existsSync(p); } catch { return false; }
}
function defaultReadFile(p) {
try { return readFileSync(p, "utf-8"); } catch { return null; }
}
/**
* Run a probe command without blocking the main process. These probes used
* execFileSync, which froze every window (and keystroke relay) for as long as
* `security`, `gh auth status` or `cursor-agent status` took — up to their
* multi-second timeouts. Never rejects; mirrors execFileSync's failure shape
* (exit code plus whatever output was captured).
*/
function runFile(command, args, options = {}) {
return new Promise((resolve) => {
let child;
try {
child = execFile(command, args, { encoding: "utf8", ...options }, (error, stdout, stderr) => {
if (!error) {
resolve({ exitCode: 0, stdout: String(stdout ?? ""), stderr: String(stderr ?? "") });
return;
}
resolve({
exitCode: typeof error.code === "number" ? error.code : 1,
stdout: String(stdout ?? ""),
stderr: String(stderr || error.message || ""),
});
});
} catch (error) {
resolve({ exitCode: 1, stdout: "", stderr: String(error?.message || error) });
return;
}
// Probes never read stdin; close it so a CLI that waits for input exits.
child?.stdin?.end();
});
}
// ── Claude ──
async function defaultRunSecurity() {
// macOS keychain lookup for the Claude Code OAuth credentials entry.
const res = await runFile(
"security",
["find-generic-password", "-s", "Claude Code-credentials", "-w"],
{ timeout: 4000 },
);
return { exitCode: res.exitCode, stdout: res.exitCode === 0 ? res.stdout : "" };
}
async function probeClaudeAuth({ env, platform, runSecurity, fileExists, homeDir } = {}) {
const e = env || process.env;
const plat = platform || process.platform;
const fx = fileExists || defaultFileExists;
const home = homeDir || os.homedir();
const apiKey = typeof e.ANTHROPIC_API_KEY === "string" ? e.ANTHROPIC_API_KEY.trim() : "";
const oauthToken = typeof e.CLAUDE_CODE_OAUTH_TOKEN === "string" ? e.CLAUDE_CODE_OAUTH_TOKEN.trim() : "";
const authToken = typeof e.ANTHROPIC_AUTH_TOKEN === "string" ? e.ANTHROPIC_AUTH_TOKEN.trim() : "";
if (apiKey || oauthToken || authToken) return { authenticated: true, authSource: "env" };
if (plat === "darwin") {
const sec = await (runSecurity || defaultRunSecurity)();
if (sec && sec.exitCode === 0 && String(sec.stdout || "").trim()) {
return { authenticated: true, authSource: "keychain" };
}
}
const configDir = typeof e.CLAUDE_CONFIG_DIR === "string" && e.CLAUDE_CONFIG_DIR.trim()
? e.CLAUDE_CONFIG_DIR.trim()
: path.join(home, ".claude");
if (fx(path.join(configDir, ".credentials.json"))) {
return { authenticated: true, authSource: "credentials-file" };
}
return { authenticated: false, authSource: null };
}
// ── Copilot ──
async function defaultRunGhAuthStatus() {
const res = await runFile("gh", ["auth", "status"], { timeout: 5000 });
if (res.exitCode === 0) return { exitCode: 0, stdout: res.stdout, stderr: "" };
return { exitCode: res.exitCode, stdout: "", stderr: res.stderr };
}
async function probeCopilotAuth({ runGhAuthStatus } = {}) {
const res = await (runGhAuthStatus || defaultRunGhAuthStatus)();
if (res && res.exitCode === 0) return { authenticated: true, authSource: "gh" };
return { authenticated: false, authSource: null };
}
// ── Codex ──
function probeCodexAuth({ runLoginStatus, fileExists, homeDir } = {}) {
const fx = fileExists || defaultFileExists;
const home = homeDir || os.homedir();
const res = runLoginStatus ? runLoginStatus() : { exitCode: 1, stdout: "" };
const out = String((res && (res.stdout || res.stderr)) || "").toLowerCase();
if (out.includes("logged in using chatgpt")) return { authenticated: true, authSource: "chatgpt" };
if (out.includes("logged in using an api key") || out.includes("logged in using api key")) {
return { authenticated: true, authSource: "api-key" };
}
if (fx(path.join(home, ".codex", "auth.json"))) {
return { authenticated: true, authSource: "auth-file" };
}
return { authenticated: false, authSource: null };
}
// ── CodeBuddy ──
// SDK supports CODEBUDDY_API_KEY, CODEBUDDY_AUTH_TOKEN (OAuth), and CLI login
// state (~/.codebuddy/settings.json with authToken/apiKeyHelper).
function probeCodebuddyAuth({ env, fileExists, readFile, homeDir } = {}) {
const e = env || process.env;
const fx = fileExists || defaultFileExists;
const rf = readFile || defaultReadFile;
const home = homeDir || os.homedir();
const apiKey = typeof e.CODEBUDDY_API_KEY === "string" ? e.CODEBUDDY_API_KEY.trim() : "";
const authToken = typeof e.CODEBUDDY_AUTH_TOKEN === "string" ? e.CODEBUDDY_AUTH_TOKEN.trim() : "";
if (apiKey) return { authenticated: true, authSource: "api-key" };
if (authToken) return { authenticated: true, authSource: "auth-token" };
// Check CLI login state in settings.json (authToken / apiKeyHelper fields).
const settingsPath = path.join(home, ".codebuddy", "settings.json");
const content = rf(settingsPath);
if (content !== null) {
try {
const parsed = JSON.parse(content);
if (parsed && typeof parsed === "object") {
if (typeof parsed.authToken === "string" && parsed.authToken.trim()) {
return { authenticated: true, authSource: "settings-file" };
}
if (typeof parsed.apiKeyHelper === "string" && parsed.apiKeyHelper.trim()) {
return { authenticated: true, authSource: "settings-file" };
}
}
} catch { /* Malformed JSON — treat as no auth */ }
}
return { authenticated: false, authSource: null };
}
// ── Cursor CLI login (cursor-agent only) ──
// Do not probe bare `agent` — it collides with other CLIs on PATH (e.g. Grok).
const CURSOR_CLI_BINARY_CANDIDATES = ["cursor-agent"];
function stripCursorApiKeyFromProbeEnv(env) {
const out = { ...(env || {}) };
delete out.CURSOR_API_KEY;
return out;
}
async function defaultResolveCursorCliBinary(name, env) {
const whichCmd = process.platform === "win32" ? "where" : "which";
const res = await runFile(whichCmd, [name], { timeout: 4000, env: env || process.env, windowsHide: true });
if (res.exitCode !== 0) return null;
const first = res.stdout.split(/\r?\n/).map((l) => l.trim()).find(Boolean);
return first || null;
}
function defaultRunCursorStatus(binPath, env) {
const spec = resolveCursorCliSpawnSpec(binPath, ["status", "--format", "json"]);
return runFile(spec.command, spec.args, {
timeout: 8000,
env: env || process.env,
shell: spec.shell,
windowsHide: true,
});
}
function extractFirstJsonObject(text) {
const raw = String(text || "").replace(/^\uFEFF/, "").trim();
if (!raw) return null;
const candidates = [raw];
const start = raw.indexOf("{");
const end = raw.lastIndexOf("}");
if (start >= 0 && end > start) {
const sliced = raw.slice(start, end + 1);
if (sliced !== raw) candidates.push(sliced);
}
for (const candidate of candidates) {
try {
const parsed = JSON.parse(candidate);
if (parsed && typeof parsed === "object") return parsed;
} catch { /* try next */ }
}
return null;
}
function parseCursorStatusJson(stdout) {
const parsed = extractFirstJsonObject(stdout);
if (!parsed) return null;
// Real Cursor status always exposes isAuthenticated and/or status.
// Reject unrelated CLIs that accept unknown flags or emit other JSON.
if (typeof parsed.isAuthenticated !== "boolean" && typeof parsed.status !== "string") {
return null;
}
return parsed;
}
/**
* Probe local Cursor Agent CLI login (subscription session).
* Resolves only `cursor-agent` (not bare `agent`) to avoid PATH collisions.
* Strips CURSOR_API_KEY so "cli-login" is not proven by a metered API key alone.
*
* @returns {{ authenticated: boolean, authSource: string|null, email: string|null, binPath: string|null }}
*/
async function probeCursorCliAuth({ env, resolveBinary, runStatus } = {}) {
const e = stripCursorApiKeyFromProbeEnv(env || process.env);
const resolve = resolveBinary || ((name) => defaultResolveCursorCliBinary(name, e));
const run = runStatus || ((bin) => defaultRunCursorStatus(bin, e));
// A resolved cursor-agent path is a user install even when status JSON is
// missing, unrecognized, or the status command throws.
let resolvedBinPath = null;
for (const name of CURSOR_CLI_BINARY_CANDIDATES) {
let binPath = null;
try {
binPath = await resolve(name);
} catch {
continue;
}
if (!binPath) continue;
if (!resolvedBinPath) resolvedBinPath = binPath;
let res = null;
try {
res = await run(binPath);
} catch {
continue;
}
if (!res) continue;
// Accept JSON even on non-zero exit if present (some CLIs exit 1 when logged out).
const parsed = parseCursorStatusJson(res.stdout);
if (!parsed) continue;
const authenticated = Boolean(
parsed.isAuthenticated === true || parsed.status === "authenticated",
);
if (!authenticated) continue;
const email = typeof parsed?.userInfo?.email === "string" ? parsed.userInfo.email : null;
return { authenticated: true, authSource: "cli-login", email, binPath };
}
return {
authenticated: false,
authSource: null,
email: null,
binPath: resolvedBinPath,
};
}
// ── Grok Build ──
function probeGrokAuth({ env, fileExists, homeDir } = {}) {
const e = env || process.env;
const fx = fileExists || defaultFileExists;
const home = homeDir || os.homedir();
const apiKey = typeof e.XAI_API_KEY === "string" ? e.XAI_API_KEY.trim() : "";
if (apiKey) return { authenticated: true, authSource: "env" };
// OAuth / account login persists under ~/.grok/auth.json (or GROK_CONFIG_DIR).
const configDir = typeof e.GROK_CONFIG_DIR === "string" && e.GROK_CONFIG_DIR.trim()
? e.GROK_CONFIG_DIR.trim()
: path.join(home, ".grok");
if (fx(path.join(configDir, "auth.json"))) {
return { authenticated: true, authSource: "auth-file" };
}
return { authenticated: false, authSource: null };
}
module.exports = {
probeClaudeAuth,
probeCopilotAuth,
probeCodexAuth,
probeCodebuddyAuth,
probeCursorCliAuth,
probeGrokAuth,
CURSOR_CLI_BINARY_CANDIDATES,
defaultRunSecurity,
defaultRunGhAuthStatus,
parseCursorStatusJson,
resolveCursorCliSpawnSpec,
};