Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix: address CodeRabbit review findings on Mistral Vibe ACP driver
JoaoPec108261180b38
diff --git a/server/drivers/acp/browser-auth.test.ts b/server/drivers/acp/browser-auth.test.tsindex 99ce9d04ed..d1f35fc572 100644--- a/server/drivers/acp/browser-auth.test.ts+++ b/server/drivers/acp/browser-auth.test.ts@@ -49,6 +49,24 @@ describe.skipIf(process.platform === "win32")("AcpBrowserAuth", () => {await auth.dispose();});+ it("holds the sign-in open past the startup window: the startup timer bounds the handshake, not the person's wait", async () => {+ const home = tempHome();+ homes.push(home);+ const ready = join(home, "ready");+ let failedMessage: string | null = null;+ const auth = new AcpBrowserAuth(spec({ args: [fakeCli], failure: (stage) => { failedMessage = stage; return stage; } }), {+ cli: process.execPath,+ environment: () => ({ ...process.env, HOME: home, FAKE_VIBE_READY: ready }),+ startupTimeoutMs: 8_000, lifetimeMs: 20_000,+ });+ const started = await auth.start();+ await new Promise((resolve) => setTimeout(resolve, 9_500));+ // The startup timer covers the handshake alone; authenticate keeps the flow open for the full window.+ expect((await auth.get(started.flowId!)).phase).toBe("waiting");+ expect(failedMessage).toBeNull();+ await auth.dispose();+ });+it("cancel ends the held flow without success", async () => {const home = tempHome();homes.push(home);diff --git a/server/drivers/acp/browser-auth.ts b/server/drivers/acp/browser-auth.tsindex e9397e2550..c5ffe9b7a9 100644--- a/server/drivers/acp/browser-auth.ts+++ b/server/drivers/acp/browser-auth.ts@@ -82,6 +82,9 @@ export class AcpBrowserAuth {private disposed = false;private readonly spec: AcpBrowserSignInSpec;private readonly options: AcpBrowserAuthOptions;+ /** The finishing flow's termination, kept controller-level so a start, sign-out or dispose that arrives+ * once `finish` cleared `flow` still waits for the old child to be down before touching credentials. */+ private stopping: Promise<unknown> | null = null;constructor(spec: AcpBrowserSignInSpec, options: AcpBrowserAuthOptions) {this.spec = spec;@@ -91,6 +94,7 @@ export class AcpBrowserAuth {async start(): Promise<ProviderAuthenticationStart> {if (this.disposed) throw new Error("This provider was removed. Refresh Settings before signing in.");if (this.flow) await this.flow.stopping;+ if (this.stopping) await this.takeStopping();if (this.flow) throw new Error(`A ${this.spec.product} sign-in is already in progress. Finish or cancel it first.`);if (this.disposed) throw new Error("This provider was removed. Refresh Settings before signing in.");return new Promise<ProviderAuthenticationStart>((resolveStart, rejectStart) => {@@ -181,6 +185,9 @@ export class AcpBrowserAuth {clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },}, INIT_TIMEOUT_MS).then((raw) => {if (this.flow !== flow) return;+ // The handshake is the startup window's whole job; the authenticate wait is the person's, and it+ // owns no timer but the expiry one (the person may take the full window to finish in the browser).+ clearTimeout(flow.startupTimer);const methods = Array.isArray((raw as { authMethods?: unknown })?.authMethods)? (raw as { authMethods: Array<{ id?: string }> }).authMethods : [];const methodId = this.spec.methodId(methods, env);@@ -208,11 +215,13 @@ export class AcpBrowserAuth {const flow = this.flow;if (flow) this.finish(flow, "cancelled", `${this.spec.product} sign-in was cancelled.`);await flow?.stopping;+ if (this.stopping) await this.takeStopping();}async dispose(): Promise<void> {this.disposed = true;await this.cancel();+ if (this.stopping) await this.takeStopping();this.flow = null;}@@ -220,9 +229,17 @@ export class AcpBrowserAuth {async signOut(): Promise<void> {if (!this.spec.removeCredentials) throw new Error(`Signing out of ${this.spec.product} is not available from here.`);if (this.flow) throw new Error(`Finish or cancel the ${this.spec.product} sign-in in progress before signing out.`);+ if (this.stopping) await this.takeStopping();await this.spec.removeCredentials(this.options.environment());}+ /** One waiter takes the outstanding termination; later callers see null. */+ private async takeStopping(): Promise<void> {+ const stopping = this.stopping;+ this.stopping = null;+ await stopping;+ }+/** Every request the engine raises is refused; a reply to this app's requests resolves or rejects its pending. */private receive(flow: Flow, pending: Map<number, { resolve(value: unknown): void; reject(error: Error): void }>, line: string) {let parsed: unknown;@@ -265,7 +282,11 @@ export class AcpBrowserAuth {flow.resolve = null;const child = flow.child;flow.child = null;- if (child) flow.stopping = this.stopChild(child);+ if (child) {+ flow.stopping = this.stopChild(child);+ this.stopping = flow.stopping;+ void flow.stopping.then(() => { if (this.stopping === flow.stopping) this.stopping = null; });+ }}private async stopChild(child: ChildProcess): Promise<boolean> {diff --git a/server/drivers/acp/mistral-vibe.test.ts b/server/drivers/acp/mistral-vibe.test.tsindex efcc52297d..4fe48cf9fd 100644--- a/server/drivers/acp/mistral-vibe.test.ts+++ b/server/drivers/acp/mistral-vibe.test.ts@@ -64,10 +64,13 @@ describe("Mistral (Vibe) ACP driver", () => {it("treats a populated whoami_cache.json or MISTRAL_API_KEY as signed in", () => {const home = join(scratch, "vibe-home");mkdirSync(home, { recursive: true });- expect(vibeSignedIn({ VIBE_HOME: home, HOME: scratch })).toBe(false);+ // A negative keychain probe: the entry (if any) is global to the machine, while this test's marker+ // lives in a temporary VIBE_HOME — the two must not decide each other's answer.+ const probe = () => false;+ expect(vibeSignedIn({ VIBE_HOME: home, HOME: scratch }, probe)).toBe(false);writeFileSync(join(home, "whoami_cache.json"), JSON.stringify({ customer_id: "cus-fixture" }));- expect(vibeSignedIn({ VIBE_HOME: home, HOME: scratch })).toBe(true);- expect(vibeSignedIn({ VIBE_HOME: join(scratch, "absent"), MISTRAL_API_KEY: "fixture-key" })).toBe(true);+ expect(vibeSignedIn({ VIBE_HOME: home, HOME: scratch }, probe)).toBe(true);+ expect(vibeSignedIn({ VIBE_HOME: join(scratch, "absent"), MISTRAL_API_KEY: "fixture-key" }, probe)).toBe(true);});it("treats an injected keychain probe as a sign-in marker (orchestration of the fresh sign-in)", () => {diff --git a/server/drivers/acp/mistral-vibe.ts b/server/drivers/acp/mistral-vibe.tsindex c490420ddb..4548f7a0a7 100644--- a/server/drivers/acp/mistral-vibe.ts+++ b/server/drivers/acp/mistral-vibe.ts@@ -16,7 +16,7 @@// item-specific thought levels prove nothing here, so variants stay off.// - `vibe-acp --version` prints "vibe-acp 3.1.1".import { execFile, execFileSync } from "node:child_process";-import { existsSync, readFileSync, rmSync } from "node:fs";+import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";import { homedir } from "node:os";import { join } from "node:path";@@ -85,15 +85,31 @@ function offeredModels(sessionConfig: unknown): { values: string[]; current?: st};}-/** Sign-out removes what the engine's own browser sign-in wrote: the whoami cache everywhere, and the- * macOS keychain entry it stores the token in. A pasted plan key in Connections is not touched. */+/** Sign-out removes what the engine's own browser sign-in wrote: the whoami cache everywhere, the+ * MISTRAL_API_KEY line of Vibe's fallback `$VIBE_HOME/.env` (its store when the OS keyring is+ * unavailable), and the macOS keychain entries it keeps the token in (current and legacy service names —+ * see vibe's utils/keyring.py). A keyring entry the CLI stored through its own backends on Linux or+ * Windows has no portable command-line delete, so the marker files here are what this app can honestly+ * clear there. A pasted plan key in Connections is not touched. */export async function removeMistralVibeSignIn(env: Record<string, string | undefined>): Promise<void> {const home = vibeHome(env);try { rmSync(join(home, "whoami_cache.json"), { force: true }); } catch {}+ try {+ const envFile = join(home, ".env");+ if (existsSync(envFile)) {+ const kept = readFileSync(envFile, { encoding: "utf8" }).split("\n").filter((line) => !/^export ?MISTRAL_API_KEY=/u.test(line));+ writeFileSync(envFile, kept.join("\n"), { mode: 0o600 });+ }+ } catch {}if (process.platform !== "darwin") return;- await new Promise<void>((resolve) => {- execFile("security", ["delete-generic-password", "-s", "ai.mistral.vibe"], { timeout: 5_000, windowsHide: true }, () => resolve());- });+ const service = env.VIBE_KEYCHAIN_SERVICE || MISTRAL_VIBE_KEYCHAIN_SERVICE;+ await Promise.all([service, "vibe"].map((name) => new Promise<void>((resolve, reject) => {+ execFile("security", ["delete-generic-password", "-s", name], { timeout: 5_000, windowsHide: true }, (error) => {+ // "The specified item could not be found" is exit 44: already gone, which is the goal met.+ if (!error || (error as NodeJS.ErrnoException & { code?: unknown }).code === 44) return resolve();+ reject(Object.assign(new Error(`The macOS keychain refused to remove the ${name} entry: ${error.message}`), { cause: error }));+ });+ })));}diff --git a/server/engine-standalone.test.ts b/server/engine-standalone.test.tsindex 681a77a0b4..546b387f51 100644--- a/server/engine-standalone.test.ts+++ b/server/engine-standalone.test.ts@@ -540,6 +540,20 @@ describe.skipIf(process.platform === "win32")("installing a standalone engine",expect(readFileSync(join(engineDir(), VERSION, "lib", "Current"), "utf8")).toBe("dylib");});+ it("refuses a link chain whose every entry alone stays inside, but composed leaves the folder", async () => {+ // folder b, a -> b/.., c -> a/../outside: each link passes the per-entry check; followed as the kernel+ // would, c lands outside the extracted folder.+ const source = mkdtempSync(join(scratch, "tar-chain-"));+ writeFileSync(join(source, "fake-engine"), script(), { mode: 0o755 });+ mkdirSync(join(source, "b"), { recursive: true });+ symlinkSync(join("b", ".."), join(source, "a"));+ symlinkSync(join("a", "..", "outside"), join(source, "c"));+ const file = join(scratch, `chain-${Math.random().toString(36).slice(2)}.tar.gz`);+ await tar.c({ gzip: true, file, cwd: source, portable: true }, ["fake-engine", "b", "a", "c"]);+ await expect(install(fixtureRelease({ [standalonePlatformKey()]: serve(readFileSync(file), "tar.gz", "fake-engine", script()) }))).rejects.toThrow(/unsafe/);+ expect(leftovers()).toEqual([]);+ });+it("clears what an interrupted install left before it starts", async () => {mkdirSync(join(engineDir(), ".staging-old", "deep"), { recursive: true });mkdirSync(binDir(), { recursive: true });diff --git a/server/engine-standalone.ts b/server/engine-standalone.tsindex 3ca5e477d6..3185716f80 100644--- a/server/engine-standalone.ts+++ b/server/engine-standalone.ts@@ -16,7 +16,7 @@ import {closeSync, createReadStream, existsSync, lstatSync, openSync, readdirSync, readFileSync, readlinkSync, readSync, realpathSync, renameSync, rmSync, unlinkSync,} from "node:fs";import { chmod, copyFile, link, lstat, mkdir, open, readdir, rename, rm, stat, symlink, unlink, writeFile, type FileHandle } from "node:fs/promises";-import { dirname, extname, isAbsolute, join, relative, resolve } from "node:path";+import { dirname, extname, isAbsolute, join, relative, resolve, sep } from "node:path";import { stripVTControlCharacters } from "node:util";import { writeFileAtomic } from "./atomic.ts";@@ -278,15 +278,18 @@ function verifiedCurrent(engineDir: string, release: StandaloneRelease): Standalif (!realDirectory(binDir)) return null;// Nothing but the program goes on PATH; a rename Windows could not finish (.old-) is never a command anyone types.if (readdirSync(binDir).some((entry) => entry !== name && !entry.startsWith(OLD_PREFIX))) return null;- const executablePath = join(binDir, name);- const program = release.launcher ? launcherTarget(executablePath, pointer.version, asset.executable) : executablePath;+ // A Windows launcher has no bin/ entry at all (see activate): the version folder itself is the PATH folder.+ const isWinLauncher = release.launcher && process.platform === "win32";+ const versionPath = isWinLauncher ? join(engineDir, pointer.version) : binDir;+ const executablePath = isWinLauncher ? executableIn(versionPath, asset.executable) : join(binDir, name);+ const program = release.launcher && !isWinLauncher ? launcherTarget(executablePath, pointer.version, asset.executable) : executablePath;if (!program || !realFile(program)) return null;try {if (hashFileSync(program) !== expected) return null;} catch {return null;}- return { version: pointer.version, executablePath, binDir };+ return { version: pointer.version, executablePath, binDir: versionPath };}/** bin/'s entry for a launcher is a link to exactly this version's program, written relative to bin/: anything else is@@ -489,6 +492,7 @@ async function extractTarGz(archivePath: string, staging: string): Promise<boolereturn true;},});+ if (!unsafe && linkChainsEscape(staging)) unsafe = true;return !unsafe;}@@ -512,6 +516,54 @@ function safeInboundLink(name: string, link: string): boolean {return steps > 0;}+/** The most splices one chain can make before cyclical links are given up on as dangling: nothing escapes behind them. */+const MAX_LINK_HOPS = 64;++/** True when a kept link, followed exactly as the kernel would (each component resolved, every link it crosses+ * spliced), leaves the extracted folder. Each entry was vetted alone (see safeInboundLink), but a chain —+ * folders `b`, `a -> b/..`, `c -> a/../out` — composes an way out no single entry shows. A link chain that+ * ends before a real file (an in-root cycle, a missing hand-off name) stays dangling, and dangles are kept. */+function linkChainsEscape(root: string): boolean {+ const notInside = (path: string): boolean => path !== root && !path.startsWith(root + sep);+ const follow = (path: string): string | null => {+ try { return lstatSync(path).isSymbolicLink() ? readlinkSync(path) : null; }+ catch { return null; }+ };+ // Components left to place, and where they hang from; a splice continues from the link's own directory.+ const chain = (from: string, target: string): boolean => {+ let queue: string[] = target.split("/");+ let path = from;+ let hops = 0;+ while (queue.length) {+ const segment = queue.shift()!;+ if (segment === "" || segment === ".") continue;+ if (segment === "..") {+ path = dirname(path);+ if (notInside(path)) return true;+ continue;+ }+ path = join(path, segment);+ if (notInside(path)) return true;+ const next = follow(path);+ if (next !== null) {+ if (++hops > MAX_LINK_HOPS) return false;+ queue = next.split("/").concat(queue);+ path = dirname(path);+ }+ }+ return false;+ };+ const walk = (dir: string): boolean => {+ for (const entry of readdirSync(dir, { withFileTypes: true })) {+ const path = join(dir, entry.name);+ if (entry.isDirectory()) { if (walk(path)) return true; }+ else if (entry.isSymbolicLink() && chain(path, readlinkSync(path))) return true;+ }+ return false;+ };+ return walk(root);+}+/** Folders 0755, files 0755 when the archive marked them executable and 0644 otherwise: no setuid, nothing writable by others. */async function normaliseModes(directory: string): Promise<void> {for (const entry of await readdir(directory, { withFileTypes: true })) {@@ -670,18 +722,22 @@ async function activate(engineDir: string, release: StandaloneRelease, asset: Stconst fresh = join(binDir, `${NEW_PREFIX}${randomUUID()}${extname(name)}`);try {if (winLauncher) {- // No bin entry to write; a folder check below keeps bin/ clean all the same.+ // No bin entry to write; a folder check below keeps bin/ clean all the same, and the program already+ // sits in the version folder from the extraction.} else if (release.launcher) {// A launcher finds the rest of its folder from where it really is, so bin/ links to it rather than holding a copy.await symlink(launcherLink(release.version, asset.executable), fresh);- } else try {- await link(source, fresh);- } catch {- // A file system without hard links gets a copy.- await copyFile(source, fresh);- if (process.platform !== "win32") await chmod(fresh, 0o755);+ await replaceFile(fresh, target);+ } else {+ try {+ await link(source, fresh);+ } catch {+ // A file system without hard links gets a copy.+ await copyFile(source, fresh);+ if (process.platform !== "win32") await chmod(fresh, 0o755);+ }+ await replaceFile(fresh, target);}- await replaceFile(fresh, target);} finally {// Renaming one hard link onto another of the same file leaves both names in place.await rm(fresh, { force: true }).catch(() => {});diff --git a/src/components/EngineSetup.tsx b/src/components/EngineSetup.tsxindex e9c8356b16..4c40e22e48 100644--- a/src/components/EngineSetup.tsx+++ b/src/components/EngineSetup.tsx@@ -560,7 +560,7 @@ export function EngineSetup({: t("engineSetup.setupTitle", { name: engineDisplayName(instance) });const description = descriptionOverride ?? (signInOnly? engineBrowserSignIn- ? t("engineSetup.engineBrowser.description")+ ? t("engineSetup.engineBrowser.description", { name: engineDisplayName(instance) }): browserSignIn? t("engineSetup.chatgpt.description"): deviceSignIn