Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(codex): keep turns working when Windows cannot share the Codex login
erywim9a8edf9b22db
diff --git a/server/drivers/codex-errors.ts b/server/drivers/codex-errors.tsindex 8432814904..d280dfd0e3 100644--- a/server/drivers/codex-errors.ts+++ b/server/drivers/codex-errors.ts@@ -12,6 +12,10 @@ export type CodexRoute = "plan" | "own" | "other";// codex-cli 0.160.1 holding no login sends no Authorization header and gets this 401.export const CODEX_MISSING_CREDENTIALS = /missing bearer or basic authentication/i;+// codex-cli 0.167.0's app-server takes a cross-process writer lock on a loaded thread (codex-rs/rollout/src/writer_lock.rs);+// a second app-server's thread/resume gets this rejection while the first still holds it.+const CODEX_THREAD_BUSY = /\bthread\b[^\n]*\balready has an active writer\b/;+export function codexNotSignedIn(): string {return `Codex isn't signed in on this computer.${cloudHomeConfigured() ? " Sign-ins don't copy over when you move to My Cloud." : ""} Sign in to Codex in Settings → AI → Providers, on Codex.`;}@@ -86,6 +90,7 @@ export function codexUserFailure(value: string, route: CodexRoute, codexErrorInfexport function codexUserError(value: string, route: CodexRoute, codexErrorInfo?: unknown): string {if (codexPlanModelRefused(value, route)) return noticeFailure("chat.notice.codexModelUnavailable").message;+ if (CODEX_THREAD_BUSY.test(value)) return codexThreadBusyHelp();if (route === "plan" && value.includes("subscription_sharing_usage_limit_exceeded")) {return "subscription_sharing_usage_limit_exceeded: Your ChatGPT plan usage limit was reached. Manage usage in ChatGPT Settings, or explicitly choose another provider.";}@@ -130,6 +135,14 @@ export class CodexRpcError extends Error {}}+/** Codex refused this thread because another Codex app or process still has it loaded. */+export const codexThreadBusy = (error: unknown): boolean =>+ error instanceof CodexRpcError && CODEX_THREAD_BUSY.test(error.message);++export function codexThreadBusyHelp(): string {+ return "This conversation is open in another Codex app or process, which still has it. Close the conversation there or quit the other Codex app, then send this message again. MausBot did not stop the other run.";+}+export function missingNativeCodexThread(error: unknown, cursor: string): boolean {// Codex's local thread/resume rejection, verified with an empty native home; unknown versions fail closed.return error instanceof CodexRpcError && error.code === -32600 &&@@ -145,3 +158,12 @@ export const codexProviderMismatch = (error: unknown): boolean =>/** Codex refuses to resume an archived session: "session <id> is archived. Run `codex unarchive <id>` to unarchive it first." */export const archivedNativeCodexThread = (error: unknown, cursor: string): boolean =>error instanceof CodexRpcError && error.message.includes(cursor) && /\bis archived\b/.test(error.message);++/** A strict-resume turn can rebuild from the chat when Codex no longer has the thread, keeps it under another provider,+ * or another Codex app or process still holds its writer lock. `busy` tells the turn which notice to show. */+export function codexResumeRebuild(error: unknown, cursor: string, recoveryText: string | undefined): { busy: boolean } | null {+ if (!recoveryText?.trim()) return null;+ const busy = codexThreadBusy(error);+ return missingNativeCodexThread(error, cursor) || archivedNativeCodexThread(error, cursor) || codexProviderMismatch(error) || busy+ ? { busy } : null;+}diff --git a/server/drivers/codex-shared-home.test.ts b/server/drivers/codex-shared-home.test.tsindex c2b4519e58..3af0c622f6 100644--- a/server/drivers/codex-shared-home.test.ts+++ b/server/drivers/codex-shared-home.test.ts@@ -4,7 +4,22 @@ import { tmpdir } from "node:os";import { dirname, join } from "node:path";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { keepChatsOutOfCodexHistory, linkSharedCodexHome } from "./codex-shared-home.ts";+// Windows without Developer Mode refuses file symlinks with EPERM while directory junctions still work.+const refusedFileLinks = vi.hoisted(() => ({ on: false }));+vi.mock("node:fs", async (importOriginal) => {+ const fs = await importOriginal<typeof import("node:fs")>();+ return {+ ...fs,+ symlinkSync: (target: Parameters<typeof fs.symlinkSync>[0], path: Parameters<typeof fs.symlinkSync>[1], type?: Parameters<typeof fs.symlinkSync>[2]) => {+ if (refusedFileLinks.on && type === "file") {+ throw Object.assign(new Error(`EPERM: operation not permitted, symlink '${String(target)}' -> '${String(path)}'`), { code: "EPERM", syscall: "symlink" });+ }+ fs.symlinkSync(target, path, type);+ },+ };+});++import { codexHomeFallbackNotice, keepChatsOutOfCodexHistory, linkSharedCodexHome } from "./codex-shared-home.ts";let root: string;let shared: string;@@ -22,6 +37,7 @@ beforeEach(() => {root = mkdtempSync(join(tmpdir(), "omb-codex-shared-home-"));shared = join(root, "person", ".codex");plan = join(root, "data", "providers", "chatgpt-plan", "abc", "codex");+ refusedFileLinks.on = false;vi.spyOn(console, "error").mockImplementation(() => {});});@@ -140,6 +156,20 @@ describe("linkSharedCodexHome", () => {expect(linkSharedCodexHome(signedOut, join(root, "fresh", "codex"), "person")).toBe(true);});+ it("still shares the folders an own-login turn uses when Windows refuses file links", () => {+ write(join(shared, "config.toml"), "person config");+ write(join(shared, "skills", "review", "SKILL.md"));+ refusedFileLinks.on = true;+ vi.spyOn(process, "platform", "get").mockReturnValue("win32");++ expect(linkSharedCodexHome(shared, plan)).toBe(true);++ // Junctions work without Developer Mode, so the folders a plan turn uses are shared; files are left alone.+ expect(linksTo(join(plan, "skills"), join(shared, "skills"))).toBe(true);+ expect(existsSync(join(plan, "config.toml"))).toBe(false);+ expect(readFileSync(join(shared, "config.toml"), "utf8")).toBe("person config");+ });+it("keeps the plan's own sign-in real and removes a link that stands in its place", () => {write(join(shared, "auth.json"), "person's sign-in");write(join(shared, "models_cache.json"), "person's models");@@ -281,6 +311,28 @@ describe("keepChatsOutOfCodexHistory", () => {expect(turnEnv({}, false, [managed]).CODEX_HOME).toBe(mausHome("codex"));});+ it("keeps the person's home, and the turn going, when Windows refuses the file link that would share their login", () => {+ write(join(shared, "auth.json"), "person's sign-in");+ write(join(shared, "config.toml"), 'model = "gpt-5"\n');+ write(join(shared, "skills", "review", "SKILL.md"));+ refusedFileLinks.on = true;+ vi.spyOn(process, "platform", "get").mockReturnValue("win32");++ const env: Record<string, string | undefined> = { HOME: join(root, "person") };+ const placement = keepChatsOutOfCodexHistory(env, "codex", data());++ // The turn still runs, in the person's own home: its chats reach their Codex history, so the caller is told.+ expect(placement).toBe("unlinked");+ expect(env.CODEX_HOME).toBeUndefined();+ expect(env.CODEX_SQLITE_HOME).toBeUndefined();+ const home = mausHome("codex");+ expect(linksTo(join(home, "skills"), join(shared, "skills"))).toBe(true);+ expect(existsSync(join(home, "auth.json"))).toBe(false);+ expect(existsSync(join(home, "config.toml"))).toBe(false);+ expect(vi.mocked(console.error).mock.calls.map((call) => String(call[0])).join(" ")).toContain('could not link "auth.json"');+ expect(codexHomeFallbackNotice()).toContain("Developer Mode");+ });+it("keeps the person's home, and the turn going, when MausBot's Codex home cannot be made", () => {write(join(shared, "auth.json"), "person's sign-in");write(join(data(), "providers", "codex-own"), "a file where a folder should be");diff --git a/server/drivers/codex-shared-home.ts b/server/drivers/codex-shared-home.tsindex 6200f1cb24..adbec25259 100644--- a/server/drivers/codex-shared-home.ts+++ b/server/drivers/codex-shared-home.ts@@ -138,22 +138,38 @@ function keyringLogin(home: string, managedConfigs: readonly string[]): booleanreturn /^\s*cli_auth_credentials_store\s*=\s*["'](?:keyring|auto)["']/m.test(topLevel);}+/** Where a turn's chats stay: MausBot's own Codex home, the person's by design, or the person's because their login could+ * not be shared into a home of MausBot's ("unlinked"). A Windows file link refused without Developer Mode is unlinked. */+export type CodexHomePlacement = "isolated" | "person" | "unlinked";+/** A turn on the person's own Codex sign-in runs in MausBot's Codex home for this instance, so its chats stay out of their* Codex and ChatGPT apps. It keeps their home when that is MausBot's already (a Team Cloud's engine homes, anything in* the data folder), when their home has no login file or their login may be in the keyring, or when their login cannot- * be linked or MausBot's home cannot be made: the turn still runs. */+ * be linked or MausBot's home cannot be made: the turn still runs. Returns where its chats stay. */export function keepChatsOutOfCodexHistory(env: Record<string, string | undefined>, instanceId: string, dataDir = DATA_DIR,- teamCloud = engineHomes.active(), managedConfigs: readonly string[] = MANAGED_CODEX_CONFIGS): void {+ teamCloud = engineHomes.active(), managedConfigs: readonly string[] = MANAGED_CODEX_CONFIGS): CodexHomePlacement {const person = codexHome(env);- if (!person || teamCloud || inside(resolve(dataDir), person) || !existsSync(join(person, "auth.json")) || keyringLogin(person, managedConfigs)) return;+ if (!person || teamCloud || inside(resolve(dataDir), person) || !existsSync(join(person, "auth.json")) || keyringLogin(person, managedConfigs)) return "person";const home = join(resolve(dataDir), "providers", "codex-own", createHash("sha256").update(instanceId).digest("hex"), "codex");try {- if (!linkSharedCodexHome(person, home, "person")) return;+ if (!linkSharedCodexHome(person, home, "person")) {+ // Never copy or hard-link auth.json instead: Codex saves a login by renaming a new file over it, so the copies+ // would split refresh tokens.+ note(home, "your Codex sign-in is not in MausBot's Codex home, so this turn uses your own home and its chats keep reaching your Codex history");+ return "unlinked";+ }} catch (error) {note(home, `could not make MausBot's Codex home, so this turn uses yours: ${(error as Error).message}`);- return;+ return "unlinked";}env.CODEX_HOME = home;// Codex keeps its databases here too unless config.toml names another folder.env.CODEX_SQLITE_HOME = home;+ return "isolated";+}++/** What a turn says when its chats cannot be kept out of the person's own Codex history. */+export function codexHomeFallbackNotice(): string {+ return `MausBot could not make a Codex home of its own that uses your sign-in, so this chat runs in your own Codex home and appears in your Codex history.${+ process.platform === "win32" ? " On Windows, turn on Developer Mode so MausBot can link your sign-in into its own home." : ""}`;}diff --git a/server/drivers/codex.test.ts b/server/drivers/codex.test.tsindex 2f4e8434be..0e31e587f8 100644--- a/server/drivers/codex.test.ts+++ b/server/drivers/codex.test.ts@@ -24,12 +24,13 @@ import { codexCliOverrides } from "./codex-process.ts";import { codexReleaseUpdate } from "./codex-update.ts";import { parseToml } from "../toml-lite.ts";import * as codexProcess from "./codex-process.ts";-import { CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, codexSignInRefused, codexUserError } from "./codex-errors.ts";+import { CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, codexSignInRefused, codexThreadBusyHelp, codexUserError } from "./codex-errors.ts";import { CODEX_USAGE_LIMIT_REACHED } from "../../shared/codex-usage-limit.ts";import { removeTempDir } from "../testing/cleanup.ts";import { TEAM_TOOLS_FAILED } from "./team-tools.ts";import { unsupportedCallsNotice } from "./codex-unsupported-calls.ts";-import { instructionsOverflowNotice, rebuiltSessionNotice } from "../resume-recovery.ts";+import { busySessionNotice, instructionsOverflowNotice, rebuiltSessionNotice } from "../resume-recovery.ts";+import { codexHomeFallbackNotice } from "./codex-shared-home.ts";import { startFakeHttpMcp, type FakeHttpMcp } from "../testing/fake-http-mcp-server.ts";import { OWN_MCP_HTTP_ENV } from "./own-mcp-http.ts";import { ownMcpHttpRoutes } from "../routes/own-mcp-http.ts";@@ -155,11 +156,11 @@ describe("CodexDriver turns (fake app-server)", () => {let scratch: string;const create = async (- opts: { mode?: string; fullAuto?: boolean; environment?: Record<string, string>; managed?: boolean; endpoint?: boolean; authMode?: "chatgpt-plan"; cli?: string } = {},+ opts: { mode?: string; fullAuto?: boolean; environment?: Record<string, string>; managed?: boolean; endpoint?: boolean; authMode?: "chatgpt-plan"; cli?: string; instanceId?: string } = {},) => {if (opts.mode) process.env.FAKE_CODEX_MODE = opts.mode;instance = await CodexDriver.create({- instanceId: "codex-test",+ instanceId: opts.instanceId ?? "codex-test",displayName: "Codex Test",environment: {...(opts.managed ? { HOME: scratch, USERPROFILE: scratch, CODEX_HOME: join(scratch, ".codex"), OPENMAUSBOT_COMPANY_API_KEY: "synthetic-company-fixture" } : {}),@@ -1348,6 +1349,71 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)expect(existsSync(join(codexHome, "sessions"))).toBe(false);});+ const unlinkedHome = (instanceId: string) => {+ const personHome = join(scratch, "person-codex");+ mkdirSync(personHome, { recursive: true });+ writeFileSync(join(personHome, "auth.json"), "{}");+ // A login MausBot's home kept from an earlier turn: the person's sign-in cannot be linked over it, as when+ // Windows refuses the file link without Developer Mode, so the turn falls back to the person's own home.+ const home = join(DATA_DIR, "providers", "codex-own", createHash("sha256").update(instanceId).digest("hex"), "codex");+ mkdirSync(home, { recursive: true });+ writeFileSync(join(home, "auth.json"), "a login of its own from an earlier turn");+ return personHome;+ };++ it("keeps a turn going in the person's own Codex home when its login cannot be shared, and says so once", async () => {+ const instanceId = "codex-test-person-home";+ const personHome = unlinkedHome(instanceId);+ const dump = join(scratch, "unlinked-home.json");+ process.env.FAKE_CODEX_DUMP = dump;+ await create({ instanceId, environment: { HOME: scratch, USERPROFILE: scratch, CODEX_HOME: personHome } });++ const first = await instance.adapter.sendTurn({ threadId: "t-unlinked-home", text: "hi" });+ await expect(recorder.until((e) => e.type === "turn.completed" && e.turnId === first.turnId)).resolves.toMatchObject({ ok: true });+ const seen = JSON.parse(readFileSync(dump, "utf8"));+ expect(seen.env.CODEX_HOME).toBe(personHome);+ expect(seen.env.CODEX_SQLITE_HOME).toBeUndefined();++ const second = await instance.adapter.sendTurn({ threadId: "t-unlinked-home", text: "again" });+ await recorder.until((e) => e.type === "turn.completed" && e.turnId === second.turnId);+ expect(recorder.events.filter((e) => e.type === "runtime.notice" && e.message === codexHomeFallbackNotice())).toHaveLength(1);+ });++ it("rebuilds the conversation from the chat when another Codex app holds its thread, instead of the writer-lock error", async () => {+ const instanceId = "codex-test-busy-thread";+ const personHome = unlinkedHome(instanceId);+ process.env.FAKE_CODEX_RESUME_ERROR = JSON.stringify({ code: -32600, message: "thread busy-thread already has an active writer" });+ const dump = join(scratch, "busy-thread.json");+ process.env.FAKE_CODEX_DUMP = dump;+ await create({ instanceId, environment: { HOME: scratch, USERPROFILE: scratch, CODEX_HOME: personHome } });++ const recoveryText = "Previous messages\nUser: go on";+ const { turnId } = await instance.adapter.sendTurn({ threadId: "t-busy-thread", text: "go on", resumeCursor: "busy-thread", recoveryText });+ await expect(recorder.until((e) => e.type === "turn.completed" && e.turnId === turnId)).resolves.toMatchObject({ ok: true });++ const seen = JSON.parse(readFileSync(dump, "utf8"));+ expect(seen.env.CODEX_HOME).toBe(personHome);+ expect(seen.calls.map((call: { method: string }) => call.method))+ .toEqual(["initialize", "initialized", "config/read", "thread/resume", "thread/start", "turn/start"]);+ expect(seen.calls.find((call: { method: string }) => call.method === "turn/start").params.input).toEqual([{ type: "text", text: recoveryText }]);+ expect(recorder.events.filter((e) => e.type === "session.started" && e.turnId === turnId)).toMatchObject([{ sessionId: "codex-thread-1", rebuilt: true }]);+ expect(recorder.events.filter((e) => e.type === "runtime.notice" && e.turnId === turnId).map((e) => (e as { message: string }).message))+ .toContain(busySessionNotice("Codex"));+ expect(recorder.events.some((e) => e.type === "runtime.error" && e.message.includes("already has an active writer"))).toBe(false);+ });++ it("explains an active-writer conflict for a turn that cannot rebuild", async () => {+ const personHome = join(scratch, "person-codex-error");+ mkdirSync(personHome, { recursive: true });+ writeFileSync(join(personHome, "auth.json"), "{}");+ process.env.FAKE_CODEX_RESUME_ERROR = JSON.stringify({ code: -32600, message: "thread busy-thread already has an active writer" });+ await create({ environment: { HOME: scratch, USERPROFILE: scratch, CODEX_HOME: personHome } });++ await instance.adapter.sendTurn({ threadId: "t-busy-no-recovery", text: "go on", resumeCursor: "busy-thread" });+ await expect(recorder.until((e) => e.type === "runtime.error")).resolves.toMatchObject({ message: codexThreadBusyHelp() });+ await expect(recorder.until((e) => e.type === "turn.completed")).resolves.toMatchObject({ ok: false });+ });+it("mounts connected apps without placing credential values in argv", async () => {await create();const dump = join(scratch, "composio.json");@@ -4399,6 +4465,9 @@ process.stdout.write(JSON.stringify({jsonrpc:'2.0',id:m.id,result})+'\\n');});`)const noBearer = "unexpected status 401 Unauthorized: Missing bearer or basic authentication in header, url: https://api.openai.com/v1/responses";expect(codexUserError(noBearer, "own")).toBe(codexNotSignedIn());expect(codexUserError(noBearer, "other")).toBe(noBearer);+ const busy = "thread 01a1f7c2-b3ae-7802-aa96-a15555ce8e3b already has an active writer";+ expect(codexUserError(busy, "own")).toBe(codexThreadBusyHelp());+ expect(codexUserError(busy, "plan")).toBe(codexThreadBusyHelp());});it("auto-retries a transient turn/start failure, then completes with one final message", async () => {diff --git a/server/drivers/codex.ts b/server/drivers/codex.tsindex 14975332e9..049f4e6aa0 100644--- a/server/drivers/codex.ts+++ b/server/drivers/codex.ts@@ -53,12 +53,12 @@ import { volatileContextNote, withContextNote } from "./prompt-split.ts";import type { ApprovalMode } from "../../shared/approval-mode.ts";import { CodexDeviceAuthController } from "./codex-device-auth.ts"; import { messageItem } from "../harness/text-items.ts";import { codexAccountEmail, codexHome } from "./codex-identity.ts";-import { keepChatsOutOfCodexHistory, linkSharedCodexHome } from "./codex-shared-home.ts";+import { codexHomeFallbackNotice, keepChatsOutOfCodexHistory, linkSharedCodexHome } from "./codex-shared-home.ts";import { mcpAppApprovalForm, mcpAppApprovalText, mcpElicitationDeclined, plainRecord } from "./codex-app-approval.ts";-import { archivedNativeCodexThread, CODEX_MISSING_CREDENTIALS, codexProviderMismatch, CODEX_SIGN_IN_EXPIRED, codexLimitFacts, codexNotSignedIn, CodexRpcError, codexSignInExpired, codexPlanModelRefused, codexPlanUnsupportedInput, codexSignInRefused, codexUserError, codexUserFailure, missingNativeCodexThread, type CodexRoute } from "./codex-errors.ts";+import { archivedNativeCodexThread, CODEX_MISSING_CREDENTIALS, CODEX_SIGN_IN_EXPIRED, CodexRpcError, codexLimitFacts, codexNotSignedIn, codexPlanModelRefused, codexPlanUnsupportedInput, codexResumeRebuild, codexSignInExpired, codexSignInRefused, codexUserError, codexUserFailure, type CodexRoute } from "./codex-errors.ts";import { codexTierOf } from "./codex-tier.ts"; import { codexLoginCheck, keptCodexLogin, readCodexLogin, storedCodexLogin } from "./codex-login.ts";import { keyRejected, noteKeyAccepted, noteKeyRejected } from "../key-rejections.ts";-import { classifyResumeFailure, instructionsOverflowNotice, mayReplay, rebuiltSessionNotice, recoveryPromptFor } from "../resume-recovery.ts";+import { classifyResumeFailure, mayReplay, recoveryPromptFor, sessionRebuildNotice } from "../resume-recovery.ts";import { extractMcpImages } from "../mcp-tool-images.ts"; import { codexImageInputs, withoutInlineImages } from "./codex-images.ts";import { parseProtocolAskQuestions, questionChoices } from "../../shared/ask-question.ts";import { codexQuestionReply, openAsyncQuestion, type CodexAsk } from "./codex-questions.ts";@@ -331,6 +331,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {}const active = new Map<string, Turn>();const warm = codexWarmSessions<{ initialized: any; approvalParams: CodexApprovalParams; rolloutPath: unknown }>(instanceId);+ let homeFallbackNoticed = false;const emit = (event: RuntimeEvent) => {for (const l of Array.from(listeners)) l(event);@@ -392,7 +393,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {// Interrupt state belongs to this turn so activity on other threads cannot cancel or revive its retry.let stopRequested = false;let promptSubmitted = false;- let recoveredMissingSession = false, droppedSession: "unsupported-input" | "instruction-overflow" | null = null;+ let recoveredSession = false, droppedSession: "unsupported-input" | "instruction-overflow" | null = null;let loginRaceRetried = false;const stopSignal = new AbortController();const { threadId } = turn;@@ -432,7 +433,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {};const launchAttempt = async (attempt: number): Promise<void> => {const env = childEnv();- const launchedLogin = chatgptTurn ? storedCodexLogin(env) : null; if (ownLogin) keepChatsOutOfCodexHistory(env, instanceId);+ const launchedLogin = chatgptTurn ? storedCodexLogin(env) : null;+ const placement = ownLogin ? keepChatsOutOfCodexHistory(env, instanceId) : "isolated";if (authBridge) Object.assign(env, authBridge.env); else if (planToken) env.OPENMAUSBOT_CHATGPT_TOKEN = planToken;const appServerArgs = ["app-server", ...(plan ? chatgptPlanCodexArgs(!!authBridge) : config.endpoint ? endpointCodexArgs(config.endpoint) : config.managed ? managedCodexArgs(config.managed) : codexSelectedProviderArgs(env, turn.model)), ...codexToolSurfaceArgs(),// Native shell snapshots can restore variables the shell policy removed.@@ -555,7 +557,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {}, "bot")));const child = connection.child;- let abandoned = false, resumedNativeThread = false;+ let abandoned = false, resumedNativeThread = false, busySession = false;let codexThreadId: string | null = null;let codexTurnId: string | null = null;let startingNativeTurn = false;@@ -1168,6 +1170,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {active.set(threadId, { stop, turnId, asks, steer: steerActiveTurn, pid: child.pid });if (attempt === 0 && !announced) emit({ ...base(threadId, turnId), type: "turn.started" });+ if (placement === "unlinked" && !homeFallbackNoticed) { homeFallbackNoticed = true; emit({ ...base(threadId, turnId), type: "runtime.notice", message: codexHomeFallbackNotice() }); }try {const initialized = reused ? reused.carried.initialized : await request("initialize", {@@ -1278,16 +1281,12 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {rolloutAt = rolloutMark(resumed?.thread?.path);resumedNativeThread = true;} catch (error) {- const failure = classifyResumeFailure({- attempted: true,- rejected: error instanceof CodexRpcError,- promptSubmitted,- producedOutput: state.sawStreamDelta,- });- if (recoveredMissingSession || stopRequested || state.settled ||- !turn.recoveryText?.trim() || !(missingNativeCodexThread(error, cursor) || archivedNativeCodexThread(error, cursor) || codexProviderMismatch(error)) || !mayReplay(failure)) throw error;- // Codex no longer has the thread, or keeps it under another provider: rebuild once, or every later turn fails the same way.- recoveredMissingSession = true;+ const failure = classifyResumeFailure({ attempted: true, rejected: error instanceof CodexRpcError, promptSubmitted, producedOutput: state.sawStreamDelta });+ const recoverable = codexResumeRebuild(error, cursor, turn.recoveryText);+ if (recoveredSession || stopRequested || state.settled || !recoverable || !mayReplay(failure)) throw error;+ // Rebuild once, or every later turn fails the same way.+ recoveredSession = true;+ busySession = recoverable.busy;const rebuild = recoveryPromptFor({ recoveryText: turn.recoveryText, currentText: turn.text, failure });rebuiltFromReplay = rebuild.replayed;promptText = rebuild.text;@@ -1327,8 +1326,8 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {promptText,);}- emit({ ...base(threadId, turnId), type: "session.started", sessionId: codexThreadId, model: startedModel ?? turn.model ?? null, ...(rebuiltFromReplay ? { rebuilt: true } : {}) });- if (rebuiltFromReplay) emit({ ...base(threadId, turnId), type: "runtime.notice", message: droppedSession === "instruction-overflow" ? instructionsOverflowNotice("Codex") : rebuiltSessionNotice("Codex") });+ emit({ ...base(threadId, turnId), type: "session.started", sessionId: codexThreadId, model: startedModel ?? turn.model ?? null, ...(rebuiltFromReplay || busySession ? { rebuilt: true } : {}) });+ if (busySession || rebuiltFromReplay) emit({ ...base(threadId, turnId), type: "runtime.notice", message: sessionRebuildNotice("Codex", busySession, droppedSession) });const turnInput = [...(promptText ? [{ type: "text" as const, text: promptText }] : []),...await codexImageInputs(turn.images),@@ -1370,7 +1369,7 @@ export const CodexDriver: ProviderDriver<CodexConfig> = {const needsAuth = refused || /(?:\b401\b|unauthorized|missing bearer|authentication required)/i.test(raw);const verdict = classifyError(failure);if (reused && !state.settled && !abandoned && !stopRequested && codexTurnId === null && earlyNotifications.length === 0) return relaunch("", reported.message, "rpc_error", true);- if (!state.settled && !abandoned && !recoveredMissingSession && !stopRequested && !needsAuth && codexTurnId === null && earlyNotifications.length === 0 && verdict.transient && attempt < RETRY_MAX_ATTEMPTS - 1 && state.sawStreamDelta === false) {+ if (!state.settled && !abandoned && !recoveredSession && !stopRequested && !needsAuth && codexTurnId === null && earlyNotifications.length === 0 && verdict.transient && attempt < RETRY_MAX_ATTEMPTS - 1 && state.sawStreamDelta === false) {return relaunch(verdict.reason, reported.message, "rpc_error");}if (!state.settled && !abandoned) {diff --git a/server/resume-recovery.ts b/server/resume-recovery.tsindex dada68c092..c2b676e453 100644--- a/server/resume-recovery.ts+++ b/server/resume-recovery.ts@@ -45,6 +45,17 @@ export function rebuiltSessionNotice(engine: string): string {return `${engine} could not reopen this conversation's session, so it went on in a new one started from the chat; results of earlier tool calls did not carry over.`;}+export function busySessionNotice(engine: string): string {+ return `${engine} could not reopen this conversation's session because another ${engine} app or process still has it open, so it went on in a new one started from the chat; results of earlier tool calls did not carry over.`;+}+export function instructionsOverflowNotice(engine: string): string {return `${engine} moved this conversation to a new session: its accumulated developer instruction blocks were close to the provider's system-prompt limit, so the superseded ones did not carry over.`;}++/** The notice for a session a driver replaced, naming a busy writer ahead of the other rebuild reasons. */+export function sessionRebuildNotice(engine: string, busy: boolean, droppedSession: string | null): string {+ return busy ? busySessionNotice(engine)+ : droppedSession === "instruction-overflow" ? instructionsOverflowNotice(engine)+ : rebuiltSessionNotice(engine);+}