Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Codex: room turns no longer fill the person's Codex history (#7317)
Milind Soni1e7a6f749b91
diff --git a/server/codex-room-history.e2e.test.ts b/server/codex-room-history.e2e.test.tsnew file mode 100644index 0000000000..e457ee35dd--- /dev/null+++ b/server/codex-room-history.e2e.test.ts@@ -0,0 +1,100 @@+// The Codex and ChatGPT apps list every saved Codex thread as the person's history. A room turn sends the whole room+// conversation and never resumes its thread, so each message would leave one more saved thread there: room turns start+// ephemeral threads. A one-to-one chat keeps one saved thread and resumes it.+import { spawn, type ChildProcess } from "node:child_process";+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { afterAll, beforeAll, expect, it } from "vitest";++import { removeTempDir, waitForExit } from "./testing/cleanup.ts";+import { workerPort } from "./testing/worker-port.ts";++const root = dirname(dirname(fileURLToPath(import.meta.url)));+const fake = join(root, "server", "testing", "fake-codex-app-server.ts");+const port = workerPort(19800, 10_000);+const base = `http://127.0.0.1:${port}`;+let home: string;+let callLog: string;+let child: ChildProcess;+let stderr = "";++const api = async (method: string, path: string, body?: unknown) => {+ const response = await fetch(`${base}${path}`, {+ method, headers: body ? { "content-type": "application/json" } : undefined,+ body: body ? JSON.stringify(body) : undefined,+ });+ return { status: response.status, body: await response.json() as any };+};++const calls = (): Array<{ method: string; params: Record<string, unknown> | null }> => existsSync(callLog)+ ? readFileSync(callLog, "utf8").trim().split("\n").filter(Boolean).map((line) => JSON.parse(line)) : [];++async function until(done: () => Promise<boolean>, what: string) {+ const deadline = Date.now() + 20_000;+ while (Date.now() <= deadline) {+ if (await done()) return;+ await new Promise((resolve) => setTimeout(resolve, 150));+ }+ throw new Error(`${what} did not happen: ${stderr.slice(-2000)}`);+}++beforeAll(async () => {+ chmodSync(fake, 0o755);+ home = mkdtempSync(join(tmpdir(), "omb-codex-room-history-"));+ const dataDir = join(home, ".openmausbot");+ mkdirSync(dataDir);+ callLog = join(home, "codex-calls.jsonl");+ writeFileSync(join(dataDir, "config.json"), JSON.stringify({ instances: {+ codex: { driver: "codex", environment: { FAKE_CODEX_MODE: "resume", FAKE_CODEX_CALL_LOG: callLog }, config: { cli: fake, fullAuto: false } },+ } }));+ child = spawn(process.execPath, [join(root, "server", "index.ts")], {+ cwd: root,+ env: { ...process.env, HOME: home, USERPROFILE: home, OMB_DATA_DIR: dataDir, CODEX_HOME: join(home, ".codex"), OMB_PORT: String(port) },+ stdio: ["ignore", "pipe", "pipe"],+ });+ child.stderr!.on("data", (data) => { stderr += data; });+ await until(async () => {+ if (child.exitCode !== null) throw new Error(`server exited: ${stderr.slice(-2000)}`);+ try { return (await fetch(`${base}/api/health`)).ok; } catch { return false; }+ }, "server start");+}, 30_000);++afterAll(async () => {+ if (child) await waitForExit(child, { signal: "SIGTERM" });+ if (home) await removeTempDir(home);+});++it("keeps room turns out of Codex's saved history and a one-to-one chat in one saved thread", async () => {+ const created = (await api("POST", "/api/bots")).body.bot;+ expect((await api("PATCH", `/api/bots/${created.id}`, { modelSelection: { instanceId: "codex", model: "fake-model" } })).status).toBe(200);+ const bot = async () => (await api("GET", "/api/bots")).body.bots.find((item: any) => item.id === created.id);+ const replies = (messages: any[]) => messages.filter((message) => message.kind === "text" && message.text === "done from fake codex").length;++ for (const [n, text] of ["first chat message", "second chat message"].entries()) {+ expect((await api("POST", `/api/bots/${created.id}/messages`, { text })).status).toBe(202);+ await until(async () => { const state = await bot(); return !state.busy && replies(state.messages) === n + 1; }, `chat reply ${n + 1}`);+ }+ // One saved thread, which the second message goes on in (from a kept app-server or by thread/resume).+ const chat = calls();+ expect(chat.filter((call) => call.method === "thread/start").map((call) => call.params?.ephemeral)).toEqual([false]);+ const chatThreads = chat.filter((call) => call.method === "turn/start").map((call) => call.params?.threadId);+ expect(chatThreads).toHaveLength(2);+ expect(new Set(chatThreads).size).toBe(1);++ const before = chat.length;+ const { group } = (await api("POST", "/api/groups", {+ name: "Planning room", memberIds: [created.id],+ setup: { bulletin: "", defaultResponder: { kind: "member", botId: created.id } },+ })).body;+ const roomReplies = async () => replies((await api("GET", `/api/threads/${group.threadId}/messages`)).body.messages);+ for (const [n, text] of ["first room message", "second room message"].entries()) {+ expect((await api("POST", `/api/groups/${group.id}/messages`, { text, threadId: group.threadId })).status).toBe(202);+ await until(async () => await roomReplies() === n + 1 && !(await bot()).busy, `room reply ${n + 1}`);+ }+ // Every room turn starts a thread Codex never writes down.+ const room = calls().slice(before);+ expect(room.filter((call) => call.method === "thread/resume")).toEqual([]);+ expect(room.filter((call) => call.method === "thread/start").map((call) => call.params?.ephemeral)).toEqual([true, true]);+}, 60_000);diff --git a/server/contracts.ts b/server/contracts.tsindex cba17efaf9..58ca3fdd36 100644--- a/server/contracts.ts+++ b/server/contracts.ts@@ -150,6 +150,9 @@ export interface SendTurnInput {resumeCursor?: unknown;/** Start without the previous native context or retained process; wins over resumeCursor. */sessionReset?: boolean;+ /** No later turn resumes this session (a room turn that sends the whole conversation each time), so a driver whose engine+ * can skip saving it does: the engine's own apps list every saved session as the person's history. */+ ephemeral?: boolean;/** Hold the startup ACK until prompt dispatch (Claude: first model activity); a retired transient setup failure or sign-in refusal may reject with TurnNotStartedError. */startupRecovery?: boolean;/** Given to a driver with `capabilities.engineAdmission`: awaited right before it starts an engine process ("process") ordiff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex fe591ef78a..904257985c 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -859,6 +859,24 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)expect(turnText(fourth)).toContain("fourth");});+ it("saves a conversation's thread but not one no later turn resumes", async () => {+ await create({ mode: "resume" });+ const threadStart = async (dumpName: string, threadId: string, ephemeral?: boolean) => {+ process.env.FAKE_CODEX_DUMP = join(scratch, dumpName);+ const { turnId } = await instance.adapter.sendTurn({+ threadId, text: "hello", system: "Stable rules.", systemStable: "Stable rules.", systemVolatile: "Memory: likes quiet hours.",+ ...(ephemeral === undefined ? {} : { ephemeral }),+ });+ await recorder.until((event) => event.type === "turn.completed" && event.turnId === turnId);+ const calls = JSON.parse(readFileSync(join(scratch, dumpName), "utf8")).calls as Array<{ method: string; params: Record<string, unknown> }>;+ return calls.filter((call) => call.method === "thread/start").map((call) => call.params.ephemeral);+ };+ // A one-to-one chat resumes its thread next turn, so Codex keeps it.+ expect(await threadStart("chat.json", "t-chat")).toEqual([false]);+ // A room turn sends the whole conversation each time and never resumes: nothing is saved, so the Codex app lists nothing.+ expect(await threadStart("room.json", "t-room", true)).toEqual([true]);+ });+it("ignores requests received after turn completion", async () => {await create({ mode: "late-request" });await instance.adapter.sendTurn({ threadId: "t-late-request", text: "finish" });diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 4233561c7c..a7a37c7ad9 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -1302,7 +1302,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {...(selection.modelProvider ? { modelProvider: selection.modelProvider } : {}),...approvalParams.thread,...(turn.guestConfined ? { environments: [] } : {}),- ephemeral: false,+ ephemeral: turn.ephemeral === true,});let started;try {diff --git a/server/host/room-sessions.test.ts b/server/host/room-sessions.test.tsindex 186e0ca13c..5614f0e7e6 100644--- a/server/host/room-sessions.test.ts+++ b/server/host/room-sessions.test.ts@@ -188,16 +188,16 @@ describe("room sessions: turns that are not managed", () => {r.state.enabled = false;r.say("Cut the intro.");const first = r.dispatch("editor");- expect(first.result).toEqual({ mode: "legacy", text: r.full(first), send: {} });+ expect(first.result).toEqual({ mode: "legacy", text: r.full(first), send: { ephemeral: true } });r.finish(first, "S1", { reply: "Done." });r.say("Trim the middle.");const second = r.dispatch("editor");- expect(second.result).toEqual({ mode: "legacy", text: r.full(second), send: {} });+ expect(second.result).toEqual({ mode: "legacy", text: r.full(second), send: { ephemeral: true } });expect(second.result.text).toContain("Omkar: Cut the intro.\nEditor: Done.\nOmkar: Trim the middle.");r.finish(second, "S1", { reply: "Trimmed." });// The 90% reset and Compact now are passed on as they always were.const reset = r.dispatch("editor", { reset: true });- expect(reset.result).toEqual({ mode: "legacy", text: r.full(reset), send: { sessionReset: true } });+ expect(reset.result).toEqual({ mode: "legacy", text: r.full(reset), send: { sessionReset: true, ephemeral: true } });r.finish(reset, "S2", { reply: "Fresh." });// Nothing was recorded while it was off: switched on, the member starts.r.state.enabled = true;@@ -229,6 +229,8 @@ describe("room sessions: turns that are not managed", () => {const tail = tailFor("editor", "\n\nYour last turn in this room ended without a final message to the room.");const main = {...(reset ? { sessionReset: true } : {}),+ // A turn that is never resumed asks the engine not to save its session.+ ...(scenario.mode === "legacy" ? { ephemeral: true } : {}),threadId: "room",botId: "editor",text: withTurnClock(CLOCK, `${recalled}\n\n${window.text + tail}`),@@ -252,11 +254,11 @@ describe("room sessions: turns that are not managed", () => {const r = room();r.say("Cut the intro.");const first = r.dispatch("editor", { instance });- expect(first.result).toEqual({ mode: "legacy", text: r.full(first), send: {} });+ expect(first.result).toEqual({ mode: "legacy", text: r.full(first), send: { ephemeral: true } });r.finish(first, "S1", { reply: "Done." });r.say("Trim the middle.");const second = r.dispatch("editor", { instance });- expect(second.result).toEqual({ mode: "legacy", text: r.full(second), send: {} });+ expect(second.result).toEqual({ mode: "legacy", text: r.full(second), send: { ephemeral: true } });}});@@ -268,7 +270,7 @@ describe("room sessions: turns that are not managed", () => {// Its record is usable here (the other tests resume at this point), and a// confined turn must neither use it nor leave it for a later turn.const confined = r.dispatch("editor", { guestConfined: true });- expect(confined.result).toEqual({ mode: "legacy", text: r.full(confined), send: {} });+ expect(confined.result).toEqual({ mode: "legacy", text: r.full(confined), send: { ephemeral: true } });r.finish(confined, "S-guest", { reply: "Confined answer." });r.say("Tighten the outro.");const after = r.dispatch("editor");@@ -599,7 +601,7 @@ describe("room sessions: when a record is not trusted", () => {const warn = vi.spyOn(console, "warn").mockImplementation(() => {});try {const turn = r.dispatch("editor", { config: cyclic });- expect(turn.result).toStrictEqual({ mode: "legacy", text: r.full(turn), send: {} });+ expect(turn.result).toStrictEqual({ mode: "legacy", text: r.full(turn), send: { ephemeral: true } });} finally { warn.mockRestore(); }});@@ -814,7 +816,7 @@ describe("room sessions: a native compaction", () => {it("is not managed without the engine-hook channel, which is how a compaction is heard of", () => {const r = ready();const turn = r.dispatch("editor", { hooks: false });- expect(turn.result).toStrictEqual({ mode: "legacy", text: r.full(turn), send: {} });+ expect(turn.result).toStrictEqual({ mode: "legacy", text: r.full(turn), send: { ephemeral: true } });r.finish(turn, "S1", { reply: "Trimmed." });r.say("Tighten the outro.");// and the record it had is gone: nothing said whether that turn compacted@@ -1299,7 +1301,7 @@ describe("room sessions: what it keeps, and that it cannot fail a turn", () => {const cyclic: unknown[] = [];cyclic.push(cyclic);const turn = r.dispatch("editor", { config: cyclic });- expect(turn.result).toStrictEqual({ mode: "legacy", text: r.full(turn), send: {} });+ expect(turn.result).toStrictEqual({ mode: "legacy", text: r.full(turn), send: { ephemeral: true } });expect(warn).not.toHaveBeenCalled();} finally { warn.mockRestore(); }});@@ -1402,11 +1404,11 @@ describe("room sessions: what it keeps, and that it cannot fail a turn", () => {const warn = vi.spyOn(console, "warn").mockImplementation(() => {});try {const turn = r.dispatch("editor", { window: broken });- expect(turn.result).toStrictEqual({ mode: "legacy", text: r.full(turn), send: {} });+ expect(turn.result).toStrictEqual({ mode: "legacy", text: r.full(turn), send: { ephemeral: true } });expect(warn).toHaveBeenCalledOnce();// the room's own reset still goes out with the fallbackconst withReset = r.dispatch("editor", { window: broken, reset: true });- expect(withReset.result).toStrictEqual({ mode: "legacy", text: r.full(withReset), send: { sessionReset: true } });+ expect(withReset.result).toStrictEqual({ mode: "legacy", text: r.full(withReset), send: { sessionReset: true, ephemeral: true } });expect(warn).toHaveBeenCalledTimes(2);} finally { warn.mockRestore(); }expect(r.sessions.tracked()).toMatchObject({ records: 0, flights: 0 });diff --git a/server/host/room-sessions.ts b/server/host/room-sessions.tsindex 611e80ec5c..7d7a2248ba 100644--- a/server/host/room-sessions.ts+++ b/server/host/room-sessions.ts@@ -51,7 +51,7 @@ export interface RoomDispatchInput {export interface RoomDispatch {mode: "legacy" | "start" | "resume";text: string;- send: { sessionReset?: true; resumeCursor?: string; recoveryText?: string };+ send: { sessionReset?: true; resumeCursor?: string; recoveryText?: string; ephemeral?: true };}export interface RoomSessions {@@ -259,7 +259,7 @@ export function createRoomSessions(deps: RoomSessionsDeps): RoomSessions {function decide(input: RoomDispatchInput, full: string, today: RoomDispatch["send"]): RoomDispatch {const { threadId, botId, instance, window } = input;- const legacy = (): RoomDispatch => ({ mode: "legacy", text: full, send: today });+ const legacy = (): RoomDispatch => ({ mode: "legacy", text: full, send: { ...today, ephemeral: true } });if (!roomSessionsEnabled(deps.settings(), deps.env)) {clear();return legacy();@@ -374,7 +374,7 @@ export function createRoomSessions(deps: RoomSessionsDeps): RoomSessions {drop(input.threadId, input.botId);} catch { /* nothing more to let go of */ }console.warn(`room sessions: sent the whole window instead on thread ${input.threadId} (${error instanceof Error ? error.message : String(error)})`);- return { mode: "legacy", text: full, send: today };+ return { mode: "legacy", text: full, send: { ...today, ephemeral: true } };}},bindTurn(threadId, claimId, turnId) {