Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(grok): read config.toml as TOML, end background work that will not close, tighten tests and docs

Krishna Dobhalbe1bbce19c2b
diff --git a/docs/verification/grok-steering.md b/docs/verification/grok-steering.md
index a5c9b8a785..569e19ad13 100644
--- a/docs/verification/grok-steering.md
+++ b/docs/verification/grok-steering.md
@@ -20,16 +20,48 @@ OpenMausBot adds the line itself, for a signed-in Grok, when a turn starts. A
## Fixture check
-Use an isolated home with a copy of the sign-in, never `~/.grok`:
+`control-omb.ts launch` starts the fake engine only and does not pass `GROK_HOME`, so
+the real CLI needs a server started by hand. Use a temporary data directory and a copy
+of the sign-in, never `~/.grok`:
-```sh
-GROK_HOME=<temp dir holding a copy of auth.json> node --experimental-strip-types scripts/control-omb.ts launch
-```
+1. Make a data directory `$D` with `$D/grokhome/` holding a copy of `~/.grok/auth.json`
+ and an empty `$D/tmp/`.
+2. Write `$D/config.json` (the server reads `config.json` from `OMB_DATA_DIR`):
-The launcher's fixture has only the fake engine, so for the real CLI start the
-server by hand with an instance `{ driver: "grokAgent", config: { cli: <grok> },
-environment: { GROK_HOME } }` in the fixture's `config.json`, and give Grok's
-shell tool a working shell. File tools need none.
+ ```json
+ {
+ "features": { "smartSetupChoices": false },
+ "instances": {
+ "grok": {
+ "driver": "grokAgent",
+ "displayName": "Grok (real)",
+ "config": { "cli": "<absolute path of the grok executable>", "fullAuto": true },
+ "environment": { "GROK_HOME": "<$D>/grokhome" }
+ }
+ }
+ }
+ ```
+
+3. Start the server with the same isolated environment the launcher builds, on a port of
+ your choice, and serve the built UI (`pnpm build` first). Run from the repository root:
+
+ ```js
+ // start-grok-fixture.mts, run with: node --experimental-strip-types start-grok-fixture.mts
+ import { spawn } from "node:child_process";
+ import { verificationServerArgs, verificationServerEnvironment } from "./scripts/control-omb.ts";
+
+ const dataDir = process.env.D, port = 19975;
+ const env = verificationServerEnvironment(process.env, dataDir, port);
+ env.OMB_STATIC_DIR = `${process.cwd()}/dist`;
+ spawn(process.execPath, verificationServerArgs(env), { env, stdio: "inherit" });
+ ```
+
+4. Open `http://127.0.0.1:19975` and create the first bot; it uses the Grok instance.
+
+Grok's shell tool needs a shell the isolated environment can find, so use its file tools
+for the check below.
+
+Then:
1. Ask the bot for 8 files, `step1.txt` to `step8.txt`, one write per file.
2. After a few exist, send "do not create any more files, reply MANGO".
@@ -38,7 +70,11 @@ shell tool a working shell. File tools need none.
Automated: `server/drivers/acp/grok-steer.test.ts` against the scripted peer
(`FAKE_ACP_MODE=grok-steer`), including `ensureGrokSteer` on a config with no
-`[ui]`, one with `[ui]`, none at all, a `"queue"` choice and a signed-out home.
+`[ui]`, one with `[ui]`, none at all, a `"queue"` choice and a signed-out home, plus the
+spellings a TOML file allows: a quoted key, a single-quoted value, a `[ui]` header with a
+comment or at the end of the file, and `ui` defined by dotted keys or an inline table
+(never written to). The reader is `grok-follow-up.ts`; a file it cannot read with
+confidence is left untouched, and steering then stays off.
## Background subagents and commands
@@ -56,6 +92,16 @@ fork and no new session id.
Costs: a background subagent's result is discarded, as with OpenCode; the next
turn pays a `session/load`.
+When it cannot end the work:
+
+- **No `sessionCapabilities.close`.** An agent that does not advertise it gets no
+ `session/close`, and the driver leaves its background work as it was: it can still wake a
+ turn nobody prompted, and that turn runs unseen.
+- **The close fails or times out.** The driver tries it once more. If that fails too, it ends
+ the session's process (the same step it takes for a session that ignores `session/cancel`),
+ which also stops the work; the thread's next turn loads its history in a new process. If
+ even that fails, the work can keep running.
+
Recorded on the real CLI (2026-11-19): a subagent launched in the background
finished after the turn and Grok then ran a turn that confirmed its file; with
`session/close` right after the turn the subagent was ended, no file was written
diff --git a/server/drivers/acp/background-work.test.ts b/server/drivers/acp/background-work.test.ts
index 7e669a718b..ff5c38debe 100644
--- a/server/drivers/acp/background-work.test.ts
+++ b/server/drivers/acp/background-work.test.ts
@@ -37,8 +37,22 @@ describe("close-ends background work", () => {
expect(noClose.sessionId).toBe("s1");
const failing = { sessionId: "s2" as string | null, cwd: "/w", initResult: capable };
- await work.end(failing, async () => { throw new Error("busy"); });
+ expect(await work.end(failing, async () => { throw new Error("busy"); })).toBe(false);
expect(failing.sessionId).toBe("s2");
expect(work.resumeCursor(undefined, null, failing)).toBeNull();
});
+
+ it("retries a failed close once, and reports when the work could not be ended", async () => {
+ const work = closeEndsBackgroundWork();
+ let attempts = 0;
+ const flaky = { sessionId: "s3" as string | null, cwd: "/w", initResult: capable };
+ expect(await work.end(flaky, async () => { if (++attempts === 1) throw new Error("busy"); return {}; })).toBe(true);
+ expect(attempts).toBe(2);
+ expect(flaky.sessionId).toBeNull();
+
+ let tries = 0;
+ const stuck = { sessionId: "s4" as string | null, cwd: "/w", initResult: capable };
+ expect(await work.end(stuck, async () => { tries++; throw new Error("busy"); })).toBe(false);
+ expect(tries).toBe(2);
+ });
});
diff --git a/server/drivers/acp/background-work.ts b/server/drivers/acp/background-work.ts
index db3544c6fe..34f6822c1d 100644
--- a/server/drivers/acp/background-work.ts
+++ b/server/drivers/acp/background-work.ts
@@ -7,8 +7,9 @@ export interface AcpBackgroundWork {
wakes(update: Record<string, any> | undefined): boolean;
/** The session a turn resumes: its stored cursor, or with none whatever ending the work left behind for this live session. */
resumeCursor(cursor: unknown, live: string | null, session?: object): string | null;
- /** Ends the session's background work and any turn it woke, keeping its history. Never throws. */
- end(session: { sessionId: string | null; cwd: string; initResult: any }, request: Request): Promise<void>;
+ /** Ends the session's background work and any turn it woke, keeping its history. Never throws. Resolves false when the work
+ * could not be ended and may still wake turns; the driver then closes the session's process. */
+ end(session: { sessionId: string | null; cwd: string; initResult: any }, request: Request): Promise<boolean | void>;
}
/** The session/update kinds a turn streams; titles, usage, compaction and command lists are not one. */
@@ -27,13 +28,17 @@ export function closeEndsBackgroundWork(): AcpBackgroundWork {
end: async (session, request) => {
const sessionId = session.sessionId;
if (!sessionId || !session.initResult?.agentCapabilities?.sessionCapabilities?.close) return;
- try {
- await request("session/close", { sessionId }, CLOSE_WAIT_MS);
- closed.set(session, sessionId);
- session.sessionId = null;
- } catch {
- // The session keeps its background work, as before.
+ for (let attempt = 0; attempt < 2; attempt++) {
+ try {
+ await request("session/close", { sessionId }, CLOSE_WAIT_MS);
+ closed.set(session, sessionId);
+ session.sessionId = null;
+ return true;
+ } catch {
+ // Tried again once; the caller hears of a second failure.
+ }
}
+ return false;
},
};
}
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index dd52c33936..4bf6dd95ee 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -407,7 +407,7 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const sessionIdle = sessionIdlePolicy("ACP");
const backgroundEnds = new Map<string, Promise<void>>(), endBackground = (threadId: string, session: AcpSession) => support.backgroundWork && !backgroundEnds.has(threadId) && session.child.exitCode === null
- && backgroundEnds.set(threadId, support.backgroundWork.end(session, (m, p, t) => session.host.request(null, m, p, t)).finally(() => backgroundEnds.delete(threadId)));
+ && backgroundEnds.set(threadId, support.backgroundWork.end(session, (m, p, t) => session.host.request(null, m, p, t)).then((ended) => { if (ended === false) void endUncancelled(threadId, session); }).finally(() => backgroundEnds.delete(threadId)));
const closeSession = (threadId: string, why: string) => {
const session = sessions.get(threadId);
if (!session || session.closing) return;
diff --git a/server/drivers/acp/grok-background.test.ts b/server/drivers/acp/grok-background.test.ts
index 40b7cd67fa..b6b79d5713 100644
--- a/server/drivers/acp/grok-background.test.ts
+++ b/server/drivers/acp/grok-background.test.ts
@@ -14,6 +14,10 @@ import { GrokAgentDriver } from "./grok.ts";
const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "../../testing/fake-acp-cli.ts");
+// The peer wakes a turn WAKE_MS after the prompt, then streams a step every STEP_MS; a check that nothing woke waits for the first
+// step and MARGIN_MS more, counted from the prompt and not from when the close was seen.
+const WAKE_MS = 300, STEP_MS = 100, STOP_WAKE_MS = 1_500, MARGIN_MS = 600;
+
const scratches: string[] = [];
afterEach(async () => { for (const dir of scratches.splice(0)) await removeTempDir(dir); });
@@ -30,7 +34,8 @@ const start = async (id: string, extra: Record<string, string> = {}) => {
enabled: true,
environment: {
GROK_HOME: join(scratch, "grok"), FAKE_ACP_MODE: "background-wake", FAKE_ACP_NO_FORK: "1", FAKE_ACP_CLOSE_ENDS_JOBS: "1",
- FAKE_ACP_WOKEN_FILE: files.woken, FAKE_ACP_RPC_APPEND_FILE: files.rpc, FAKE_ACP_STEP_MS: "100", ...extra,
+ FAKE_ACP_WOKEN_FILE: files.woken, FAKE_ACP_RPC_APPEND_FILE: files.rpc,
+ FAKE_ACP_WAKE_MS: String(WAKE_MS), FAKE_ACP_STEP_MS: String(STEP_MS), ...extra,
},
config: { cli: FAKE_CLI, fullAuto: true },
} as never) as ProviderInstance;
@@ -58,11 +63,12 @@ describe("Grok background work", () => {
const { instance, recorder, calls, steps, ask } = await start("grok-background-wake");
const threadId = "t-grok-background-wake";
try {
+ const startedAt = Date.now();
expect(await ask(threadId, "build it")).toMatchObject({ ok: true });
const session = promptedSession(calls)!;
await until(() => calls().some((call) => call.method === "session/close" && call.sessionId === session));
const woken = steps();
- await pause(400);
+ await pause(Math.max(0, startedAt + WAKE_MS + STEP_MS + MARGIN_MS - Date.now()));
expect(steps()).toBe(woken);
expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");
expect(recorder.events.filter((event) => event.type === "turn.completed")).toHaveLength(1);
@@ -79,8 +85,30 @@ describe("Grok background work", () => {
}
});
+ it("closes the session's process when its background work cannot be ended, so no turn wakes unseen", async () => {
+ const { instance, recorder, calls, steps, ask } = await start("grok-background-stuck", { FAKE_ACP_SESSION_CLOSE: "error", FAKE_ACP_CLOSE_ENDS_JOBS: "0" });
+ const threadId = "t-grok-background-stuck";
+ try {
+ expect(await ask(threadId, "build it")).toMatchObject({ ok: true });
+ const session = promptedSession(calls)!;
+ await until(() => calls().filter((call) => call.method === "session/close" && call.sessionId === session).length >= 2);
+ let last = -1;
+ for (let i = 0; steps() !== last; i++) {
+ if (i > 40) throw new Error("the woken turn never stopped");
+ last = steps();
+ await pause(300);
+ }
+ expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");
+ expect(await ask(threadId, "and now?")).toMatchObject({ ok: true });
+ expect(JSON.stringify(recorder.events)).not.toContain("WOKEN");
+ } finally {
+ recorder.stop();
+ await instance.dispose();
+ }
+ });
+
it("ends the session's background work when the person stops the turn, before it can wake a turn", async () => {
- const { instance, recorder, calls, steps, ask } = await start("grok-background-stop", { FAKE_ACP_WAKE_MS: "1500" });
+ const { instance, recorder, calls, steps, ask } = await start("grok-background-stop", { FAKE_ACP_WAKE_MS: String(STOP_WAKE_MS) });
const threadId = "t-grok-background-stop";
try {
const { turnId } = await instance.adapter.sendTurn({ threadId, text: "build it STOP_ME" });
@@ -90,7 +118,7 @@ describe("Grok background work", () => {
expect(await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId)).toMatchObject({ stopReason: "cancelled" });
const session = promptedSession(calls)!;
await until(() => calls().some((call) => call.method === "session/close" && call.sessionId === session));
- await pause(Math.max(0, 1_800 - (Date.now() - startedAt)));
+ await pause(Math.max(0, STOP_WAKE_MS + STEP_MS + MARGIN_MS - (Date.now() - startedAt)));
expect(steps()).toBe(0);
expect(await ask(threadId, "go on")).toMatchObject({ ok: true });
expect(promptedSession(calls)).toBe(session);
diff --git a/server/drivers/acp/grok-follow-up.test.ts b/server/drivers/acp/grok-follow-up.test.ts
new file mode 100644
index 0000000000..6ab9fc2b33
--- /dev/null
+++ b/server/drivers/acp/grok-follow-up.test.ts
@@ -0,0 +1,51 @@
+import { describe, expect, it } from "vitest";
+import { readGrokFollowUp } from "./grok-follow-up.ts";
+
+const read = (text: string) => readGrokFollowUp(text);
+
+describe("Grok's ui.follow_up_behavior in config.toml", () => {
+ it("reads basic and literal strings, bare and quoted keys, and comments after the value", () => {
+ for (const line of [
+ 'follow_up_behavior = "steer"',
+ "follow_up_behavior = 'steer'",
+ '"follow_up_behavior" = "steer"',
+ "'follow_up_behavior' = 'steer'",
+ 'follow_up_behavior = "steer" # while a turn runs',
+ ' follow_up_behavior = "steer" ',
+ ]) {
+ expect(read(`[ui]\n${line}\n`), line).toMatchObject({ present: true, value: "steer" });
+ }
+ expect(read('[ui]\nfollow_up_behavior = "queue"\n')).toMatchObject({ present: true, value: "queue" });
+ expect(read("[ui]\nfollow_up_behavior = true\n")).toMatchObject({ present: true, value: undefined });
+ });
+
+ it("reads the key from a [ui] header with a comment or spaces, a dotted key, and an inline table", () => {
+ expect(read('[ui] # display settings\nfollow_up_behavior = "steer"\n')).toMatchObject({ value: "steer" });
+ expect(read('[ ui ]\nfollow_up_behavior = "steer"\n')).toMatchObject({ value: "steer" });
+ expect(read('["ui"]\nfollow_up_behavior = "steer"\n')).toMatchObject({ value: "steer" });
+ expect(read('ui.follow_up_behavior = "steer"\n')).toMatchObject({ present: true, value: "steer", uiElsewhere: true });
+ expect(read('"ui"."follow_up_behavior" = \'steer\'\n')).toMatchObject({ present: true, value: "steer" });
+ expect(read('ui = { screen_mode = "minimal", follow_up_behavior = "steer" }\n')).toMatchObject({ present: true, value: "steer", uiElsewhere: true });
+ });
+
+ it("ignores a key of the same name in any other table", () => {
+ expect(read('[other]\nfollow_up_behavior = "steer"\n')).toMatchObject({ present: false });
+ expect(read('[ui.sub]\nfollow_up_behavior = "steer"\n')).toMatchObject({ present: false });
+ expect(read('[[marketplace.sources]]\nfollow_up_behavior = "steer"\n')).toMatchObject({ present: false });
+ expect(read('[other]\nx = 1\n[ui]\nfollow_up_behavior = "queue"\n')).toMatchObject({ value: "queue" });
+ });
+
+ it("places an insertion point at the end of the [ui] header line", () => {
+ const text = '[a]\nx = 1\n[ui] # display\nscreen_mode = "minimal"\n';
+ expect(text.slice(read(text).insertAt!)).toBe('screen_mode = "minimal"\n');
+ expect(read("[ui]").insertAt).toBe(4);
+ expect(read("[ui]\r\nscreen_mode = 1\r\n").insertAt).toBe(6);
+ expect(read("x = 1\n").insertAt).toBeUndefined();
+ });
+
+ it("steps over multi-line arrays and tables, and reports what it cannot place", () => {
+ expect(read('args = [\n "a",\n "[ui]",\n]\n[ui]\nfollow_up_behavior = "steer"\n')).toMatchObject({ value: "steer", unclear: false });
+ expect(read('note = """\n[ui]\n"""\n')).toMatchObject({ unclear: true });
+ expect(read("this is not toml\n")).toMatchObject({ unclear: true });
+ });
+});
diff --git a/server/drivers/acp/grok-follow-up.ts b/server/drivers/acp/grok-follow-up.ts
new file mode 100644
index 0000000000..a944b2f6a8
--- /dev/null
+++ b/server/drivers/acp/grok-follow-up.ts
@@ -0,0 +1,98 @@
+// The one setting of Grok's config.toml the driver reads, `ui.follow_up_behavior`, read the way TOML spells it: bare or quoted
+// keys, `[ui]` or dotted `ui.follow_up_behavior` or an inline `ui = { ... }`, basic or literal strings, comments after a value
+// or a header. A line this reader cannot place ends the scan as "unclear", and the driver never writes then.
+
+export interface GrokFollowUp {
+ /** The key is set somewhere, whatever its value's type. */
+ present: boolean;
+ /** Its string value. */
+ value?: string;
+ /** Where a line goes to land inside an existing `[ui]` table: the end of its header line. */
+ insertAt?: number;
+ /** `ui` is defined by dotted keys or an inline table, so a `[ui]` table cannot be added. */
+ uiElsewhere: boolean;
+ /** The scan met something it cannot place. */
+ unclear: boolean;
+}
+
+const BARE = "[A-Za-z0-9_-]+";
+const KEY = `(?:${BARE}|"(?:[^"\\\\]|\\\\.)*"|'[^']*')`;
+const PATH = `${KEY}(?:\\s*\\.\\s*${KEY})*`;
+const HEADER = new RegExp(`^\\s*(\\[\\[?)\\s*(${PATH})\\s*\\]\\]?\\s*(?:#.*)?$`);
+const ASSIGN = new RegExp(`^\\s*(${PATH})\\s*=\\s*(.*)$`);
+const INLINE_KEY = /(?:^|[{,])\s*(?:follow_up_behavior|"follow_up_behavior"|'follow_up_behavior')\s*=\s*(.*)$/;
+
+const unescape = (text: string) => text.replace(/\\(.)/g, "$1");
+const unquote = (key: string) => key.startsWith('"') ? unescape(key.slice(1, -1)) : key.startsWith("'") ? key.slice(1, -1) : key;
+const keyPath = (path: string): string[] => (path.match(new RegExp(KEY, "g")) ?? []).map(unquote);
+const same = (a: string[], b: string[]) => a.length === b.length && a.every((part, i) => part === b[i]);
+
+function basicStringEnd(text: string, open: number): number {
+ for (let i = open + 1; i < text.length; i++) {
+ if (text[i] === "\\") i++;
+ else if (text[i] === '"') return i;
+ }
+ return -1;
+}
+
+/** A string value at the start of `text`, or undefined when it is another kind of value or does not close on this line. */
+function stringValue(text: string): string | undefined {
+ if (text[0] === "'") { const end = text.indexOf("'", 1); return end > 0 ? text.slice(1, end) : undefined; }
+ if (text[0] !== '"') return undefined;
+ const end = basicStringEnd(text, 0);
+ return end > 0 ? unescape(text.slice(1, end)) : undefined;
+}
+
+/** How many brackets and braces a value leaves open, ignoring strings and a trailing comment. */
+function openDepth(text: string): number {
+ let depth = 0;
+ for (let i = 0; i < text.length; i++) {
+ const c = text[i];
+ if (c === "#") break;
+ if (c === '"' || c === "'") {
+ const close = c === '"' ? basicStringEnd(text, i) : text.indexOf("'", i + 1);
+ if (close < 0) return depth;
+ i = close;
+ } else if (c === "[" || c === "{") depth++;
+ else if (c === "]" || c === "}") depth--;
+ }
+ return depth;
+}
+
+export function readGrokFollowUp(text: string): GrokFollowUp {
+ const result: GrokFollowUp = { present: false, uiElsewhere: false, unclear: false };
+ const lines = text.split("\n");
+ const ends: number[] = [];
+ let at = 0;
+ for (const raw of lines) { at += raw.length + 1; ends.push(Math.min(at, text.length)); }
+ let table: string[] | null = [];
+ for (let i = 0; i < lines.length; i++) {
+ const line = lines[i].replace(/\r$/, "");
+ if (/^\s*(#.*)?$/.test(line)) continue;
+ const header = HEADER.exec(line);
+ if (header) {
+ table = header[1] === "[[" ? null : keyPath(header[2]);
+ if (table && same(table, ["ui"]) && result.insertAt === undefined) result.insertAt = ends[i];
+ continue;
+ }
+ const assign = ASSIGN.exec(line);
+ if (!assign) { result.unclear = true; return result; }
+ let rest = assign[2].trim();
+ if (rest.startsWith('"""') || rest.startsWith("'''")) { result.unclear = true; return result; }
+ while (openDepth(rest) > 0 && i + 1 < lines.length) rest += " " + lines[++i].replace(/\r$/, "").trim();
+ if (table === null) continue;
+ const path = [...table, ...keyPath(assign[1])];
+ if (same(path, ["ui", "follow_up_behavior"])) {
+ result.present = true;
+ result.value = stringValue(rest);
+ if (table.length === 0) result.uiElsewhere = true;
+ } else if (same(path, ["ui"]) && rest.startsWith("{")) {
+ result.uiElsewhere = true;
+ const inner = INLINE_KEY.exec(rest);
+ if (inner) { result.present = true; result.value = stringValue(inner[1].trim()); }
+ } else if (path[0] === "ui" && table.length === 0 && path.length > 1) {
+ result.uiElsewhere = true;
+ }
+ }
+ return result;
+}
diff --git a/server/drivers/acp/grok-steer.test.ts b/server/drivers/acp/grok-steer.test.ts
index d9a4132a17..64ee9b14c8 100644
--- a/server/drivers/acp/grok-steer.test.ts
+++ b/server/drivers/acp/grok-steer.test.ts
@@ -1,5 +1,5 @@
// Steering a running Grok turn with a second session/prompt, against the scripted ACP peer.
-import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { fileURLToPath } from "node:url";
@@ -9,7 +9,7 @@ import { ensureDirs } from "../../config.ts";
import type { AnyProviderDriver, ProviderInstance } from "../../contracts.ts";
import { removeTempDir } from "../../testing/cleanup.ts";
import { recordEvents, type EventRecorder } from "../../testing/events.ts";
-import { ensureGrokSteer, GrokAgentDriver } from "./grok.ts";
+import { ensureGrokSteer, GROK_STEER, GrokAgentDriver } from "./grok.ts";
const FAKE_CLI = join(dirname(fileURLToPath(import.meta.url)), "../../testing/fake-acp-cli.ts");
@@ -157,4 +157,44 @@ describe("ensureGrokSteer", () => {
ensureGrokSteer(env());
expect(existsSync(home())).toBe(false);
});
+
+ it("keeps a choice written with a quoted key or a single-quoted value", () => {
+ signedIn();
+ for (const text of ['[ui]\n"follow_up_behavior" = "queue"\n', "[ui]\nfollow_up_behavior = 'steer'\n"]) {
+ writeFileSync(config(), text);
+ ensureGrokSteer(env());
+ expect(readFileSync(config(), "utf8")).toBe(text);
+ }
+ });
+
+ it("adds the key under a [ui] header that has a comment, or that ends the file without a newline", () => {
+ signedIn();
+ writeFileSync(config(), '[ui] # display settings\nscreen_mode = "minimal"\n');
+ ensureGrokSteer(env());
+ expect(readFileSync(config(), "utf8")).toBe('[ui] # display settings\nfollow_up_behavior = "steer"\nscreen_mode = "minimal"\n');
+
+ writeFileSync(config(), "[ui]");
+ ensureGrokSteer(env());
+ expect(readFileSync(config(), "utf8")).toBe('[ui]\nfollow_up_behavior = "steer"\n');
+ });
+
+ it("writes nothing when ui is defined another way, or the file cannot be read with confidence", () => {
+ signedIn();
+ for (const text of ['ui.screen_mode = "minimal"\n', 'ui = { screen_mode = "minimal" }\n', 'note = """\n[ui]\n"""\n']) {
+ writeFileSync(config(), text);
+ ensureGrokSteer(env());
+ expect(readFileSync(config(), "utf8"), text).toBe(text);
+ }
+ });
+
+ it("reads a single-quoted steer, and leaves no temporary file behind", () => {
+ signedIn();
+ writeFileSync(config(), "[ui]\nfollow_up_behavior = 'steer'\n");
+ expect(GROK_STEER.enabled!(env())).toBe(true);
+ writeFileSync(config(), '[other]\nfollow_up_behavior = "steer"\n');
+ expect(GROK_STEER.enabled!(env())).toBe(false);
+ ensureGrokSteer(env());
+ expect(readFileSync(config(), "utf8")).toBe('[other]\nfollow_up_behavior = "steer"\n\n[ui]\nfollow_up_behavior = "steer"\n');
+ expect(readdirSync(home()).filter((name) => name.endsWith(".tmp"))).toEqual([]);
+ });
});
diff --git a/server/drivers/acp/grok.ts b/server/drivers/acp/grok.ts
index 179cea1575..2c8053e03c 100644
--- a/server/drivers/acp/grok.ts
+++ b/server/drivers/acp/grok.ts
@@ -1,6 +1,6 @@
// Grok Build: the official `grok` CLI over ACP stdio (`grok … agent stdio`) on the grok.com
// subscription login (~/.grok/auth.json), not the xAI API key. Verified against grok 1.0.0.
-import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
+import { existsSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { setTimeout as delay } from "node:timers/promises";
import { parse as parseYaml } from "yaml";
@@ -11,6 +11,7 @@ import type { DeviceSignIn, DeviceSignInState } from "../device-auth.ts";
import { decodeInjectId, hostApiKey, localHost, mergeLocalInject } from "../local-inject.ts";
import { createAcpDriver, type AcpSupport } from "./core.ts";
import { closeEndsBackgroundWork } from "./background-work.ts";
+import { readGrokFollowUp } from "./grok-follow-up.ts";
import type { AcpPromptSteer } from "./steer.ts";
import { bundledEngineCatalog } from "../../model-manifest/bundled.ts";
import { currentEngineCatalog } from "../../model-manifest/manifest.ts";
@@ -347,7 +348,7 @@ export const GROK_STEER: AcpPromptSteer = {
kind: "prompt",
enabled: (env) => {
try {
- return /^\s*follow_up_behavior\s*=\s*"steer"/m.test(readFileSync(join(grokHome(env), "config.toml"), "utf8"));
+ return readGrokFollowUp(readFileSync(join(grokHome(env), "config.toml"), "utf8")).value === "steer";
} catch {
return false;
}
@@ -369,15 +370,17 @@ export function ensureGrokSteer(env: Record<string, string | undefined> = proces
} catch (error) {
if ((error as NodeJS.ErrnoException).code !== "ENOENT") return;
}
- if (/^\s*follow_up_behavior\s*=/m.test(text)) return;
+ const found = readGrokFollowUp(text);
+ if (found.present || found.unclear || (found.insertAt === undefined && found.uiElsewhere)) return;
const eol = text.includes("\r\n") ? "\r\n" : "\n";
const line = `follow_up_behavior = "steer"${eol}`;
- const header = /^\[ui\][ \t]*\r?\n/m.exec(text);
- const next = header
- ? text.slice(0, header.index + header[0].length) + line + text.slice(header.index + header[0].length)
+ const next = found.insertAt !== undefined
+ ? text.slice(0, found.insertAt) + (text.slice(0, found.insertAt).endsWith("\n") ? "" : eol) + line + text.slice(found.insertAt)
: `${text}${text && !text.endsWith("\n") ? eol : ""}${text ? eol : ""}[ui]${eol}${line}`;
try {
- writeFileSync(path, next);
+ const staged = `${path}.omb-${process.pid}.tmp`;
+ writeFileSync(staged, next);
+ renameSync(staged, path);
} catch {
// Grok then keeps queueing mid-turn messages, its default.
}
diff --git a/server/testing/fake-acp-cli.ts b/server/testing/fake-acp-cli.ts
index c45fe1955a..e5f6982292 100755
--- a/server/testing/fake-acp-cli.ts
+++ b/server/testing/fake-acp-cli.ts
@@ -989,7 +989,7 @@ function handle(msg: any) {
break;
}
case "session/close":
- endWokenStep(msg.params?.sessionId);
+ if (process.env.FAKE_ACP_SESSION_CLOSE !== "error") endWokenStep(msg.params?.sessionId);
if (process.env.FAKE_ACP_CLOSE_ENDS_JOBS === "1") {
const job = backgroundJobs.get(String(msg.params?.sessionId))?.job;
if (job) clearTimeout(job);