← reports

#6866 · Codex child processes ignore the selected session home

BugPriority: MediumEffort: Mediumproviders · provider-codex · confirmed-reproGitHub issue

November 2, 2026 · trusted origin/main de578a74eef20cc15c2bb68d890e7e9bce55a68e

Verdict: REPRODUCED · Root-cause confidence: high

1. TL;DR

The native Codex bridge receives an environment override selecting a different Codex home, but the child app-server process does not receive it. The launch helper starts with the bridge environment and forwards only two Account Pool routing variables from the supplied session environment. Actual child-process probes reproduce this on start, resume, fork, model discovery, and two simultaneously open sessions. A changed home also does not invalidate a live session, so a subsequent turn can continue in the old child process. This verifies the launch and lifecycle defects, not a real wrong-account inference request or macOS desktop workflow.

2. Claims vs findings

ClaimStatusObserved evidence
A supplied CODEX_HOME loses to the inherited value.VerifiedSix start/resume/fork cases: with an inherited home, the child records home-a instead of home-b; without one, it records null.
Model discovery has the same problem.Verifiedmodel/list succeeds, but its real child process records home-a instead of selected home-b.
Two live sessions cannot independently select homes.Verified at the bridge boundaryTwo live app-server children receive [home-a, home-a], not [home-a, home-b]. Two full BB projects were not created.
A home change needs lifecycle handling.VerifiedStarting in home-a and supplying home-b to turn/start succeeds without launching a home-b process.
Default launch behavior remains valid.Verified controlBoth no-override controls pass: inherited home-a is preserved, and no inherited home remains absent.
A real account switch, missing rollout, or conversation loss occurs.UnverifiedNo credentials, native Codex installation, account API, inference endpoint, or real rollout was used.

3. Environment and isolation

4. Minimal reproduction

  1. Create a clean checkout of the pinned trusted commit and install/build its existing dependencies:
    git clone https://github.com/get-bb/bb.git bb-6866-repro
    cd bb-6866-repro
    git checkout --detach de578a74eef20cc15c2bb68d890e7e9bce55a68e
    pnpm install --frozen-lockfile --prefer-offline
    pnpm exec turbo run build --filter=bb-plugin-provider-codex
    
  2. Save the complete test below as plugins/provider-codex/src/bridge/bridge.home-selection.test.ts. It uses existing bridge test APIs and the repository's own fake Codex app-server; it does not export or copy the private launch helper.
  3. Run:
    pnpm exec turbo run test --filter=bb-plugin-provider-codex -- src/bridge/bridge.home-selection.test.ts
    Expected after a correct repair: all 11 tests pass. Actual on unchanged production code: exit 1, nine selected-home/lifecycle failures and two default-home controls passing.
   × passes the selected home to thread/start with inherited home true 92ms
   × passes the selected home to thread/start with inherited home false 54ms
   × passes the selected home to thread/resume with inherited home true 54ms
   × passes the selected home to thread/resume with inherited home false 46ms
   × passes the selected home to thread/fork with inherited home true 54ms
   × passes the selected home to thread/fork with inherited home false 51ms
   ✓ preserves the default launch with inherited home true 46ms
   ✓ preserves the default launch with inherited home false 57ms
   × uses the selected home for model discovery 61ms
   × isolates home selection for two concurrently open sessions 98ms
   × does not silently run a turn in the previous home after selection changes 57ms
Expected: "/tmp/bb-home-selection-EXAMPLE/home-b"
Received: "/tmp/bb-home-selection-EXAMPLE/home-a"
 Test Files  1 failed (1)
      Tests  9 failed | 2 passed (11)

Only temporary directory identifiers in output are normalized to EXAMPLE. Test counts and failure assertions are otherwise preserved. The representative lifecycle mismatch is:

Expected: "/tmp/bb-home-selection-EXAMPLE/home-b"
Received: "/tmp/bb-home-selection-EXAMPLE/home-a"
Complete executable reproduction test
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import { experimental_createBridgeJsonRpcTestHarness as createBridgeJsonRpcTestHarness } from "@get-bb/plugin-sdk/provider-bridge/testing";
import { z } from "zod";
import { experimental_killAllChildrenForTests, handleLine } from "./bridge.js";
import { FULL_ACCESS_SESSION_OPTIONS } from "./fake-codex-app-server-harness.js";

let harness: ReturnType<typeof createBridgeJsonRpcTestHarness>;
let workspaceDir: string;
let launchLogPath: string;
let inheritedHome: string;
let selectedHome: string;

beforeEach(() => {
  workspaceDir = mkdtempSync(join(tmpdir(), "bb-home-selection-"));
  launchLogPath = join(workspaceDir, "homes.jsonl");
  inheritedHome = join(workspaceDir, "home-a");
  selectedHome = join(workspaceDir, "home-b");
  const launcherPath = join(workspaceDir, "capture-home.mjs");
  const fakeServerUrl = new URL("./fake-codex-app-server.mjs", import.meta.url)
    .href;
  writeFileSync(
    launcherPath,
    [
      'import { appendFileSync } from "node:fs";',
      "appendFileSync(" +
        JSON.stringify(launchLogPath) +
        ', JSON.stringify(process.env.CODEX_HOME ?? null) + "\\n");',
      "await import(" + JSON.stringify(fakeServerUrl) + ");",
    ].join("\n"),
  );
  vi.stubEnv("CODEX_HOME", inheritedHome);
  vi.stubEnv("CODEX_OPENAI_BASE_URL", undefined);
  vi.stubEnv("CODEX_POOL_AUTH_TOKEN", undefined);
  vi.stubEnv("BB_CODEX_BRIDGE_APP_SERVER_COMMAND", process.execPath);
  vi.stubEnv("BB_CODEX_BRIDGE_APP_SERVER_ARGS", JSON.stringify([launcherPath]));
  harness = createBridgeJsonRpcTestHarness(handleLine);
});

afterEach(() => {
  experimental_killAllChildrenForTests();
  harness.restore();
  vi.unstubAllEnvs();
  rmSync(workspaceDir, { recursive: true, force: true });
});

function launchedHomes(): Array<string | null> {
  return readFileSync(launchLogPath, "utf8")
    .trim()
    .split("\n")
    .map((line) => z.string().nullable().parse(JSON.parse(line)));
}

async function startSession(requestId: number, home: string | undefined) {
  harness.sendRequest(requestId, "thread/start", {
    threadId: "thr_home_" + requestId,
    cwd: workspaceDir,
    instructionMode: "append",
    options: {
      ...FULL_ACCESS_SESSION_OPTIONS,
      ...(home === undefined ? {} : { envVars: { CODEX_HOME: home } }),
    },
  });
  const response = await harness.waitForResponse(requestId);
  expect(response.error).toBeUndefined();
  return z.object({ providerThreadId: z.string() }).parse(response.result);
}

it.each([
  ["thread/start", true],
  ["thread/start", false],
  ["thread/resume", true],
  ["thread/resume", false],
  ["thread/fork", true],
  ["thread/fork", false],
] as const)(
  "passes the selected home to %s with inherited home %s",
  async (method, inherited) => {
    if (!inherited) vi.stubEnv("CODEX_HOME", undefined);
    harness.sendRequest(1, method, {
      threadId: "thr_home_1",
      providerThreadId: "home-source",
      sourceProviderThreadId: "home-source",
      cwd: workspaceDir,
      instructionMode: "append",
      options: {
        ...FULL_ACCESS_SESSION_OPTIONS,
        envVars: { CODEX_HOME: selectedHome },
      },
    });
    expect((await harness.waitForResponse(1)).error).toBeUndefined();
    expect(launchedHomes()).toEqual([selectedHome]);
  },
  30_000,
);

it.each([true, false])(
  "preserves the default launch with inherited home %s",
  async (inherited) => {
    if (!inherited) vi.stubEnv("CODEX_HOME", undefined);
    await startSession(1, undefined);
    expect(launchedHomes()).toEqual([inherited ? inheritedHome : null]);
  },
  30_000,
);

it("uses the selected home for model discovery", async () => {
  harness.sendRequest(1, "model/list", {
    envVars: { CODEX_HOME: selectedHome },
  });
  expect((await harness.waitForResponse(1)).error).toBeUndefined();
  expect(launchedHomes()).toEqual([selectedHome]);
}, 30_000);

it("isolates home selection for two concurrently open sessions", async () => {
  await startSession(1, inheritedHome);
  await startSession(2, selectedHome);
  expect(launchedHomes()).toEqual([inheritedHome, selectedHome]);
}, 30_000);

it("does not silently run a turn in the previous home after selection changes", async () => {
  const started = await startSession(1, inheritedHome);
  harness.sendRequest(2, "turn/start", {
    threadId: "thr_home_1",
    providerThreadId: started.providerThreadId,
    clientRequestId: "creq_abcdefghij",
    input: [{ type: "text", text: "ok", mentions: [] }],
    options: {
      ...FULL_ACCESS_SESSION_OPTIONS,
      envVars: { CODEX_HOME: selectedHome },
    },
  });
  const response = await harness.waitForResponse(2);
  expect(response.error).toBeUndefined();
  expect(launchedHomes().at(-1)).toBe(selectedHome);
}, 30_000);

The reproduction is deliberately inline: the reports repository prohibits committed test files, raw logs, and per-issue artifact directories. Local evidence remains outside the public reports repository.

5. Root cause

appServerLaunchEnv and buildAppServerEnv show that the incoming environment is not generally merged. The helper preserves process.env and selectively overlays only CODEX_OPENAI_BASE_URL and CODEX_POOL_AUTH_TOKEN. CODEX_HOME never reaches the environment sanitizer as a supplied override:

function appServerLaunchEnv(
  envVars: Readonly<Record<string, string>> | undefined,
): NodeJS.ProcessEnv {
  const poolBaseUrl = envVars?.[CODEX_POOL_BASE_URL_ENV];
  const poolAuthToken = envVars?.[CODEX_POOL_AUTH_TOKEN_ENV];
  return {
    ...process.env,
    ...(poolBaseUrl === undefined
      ? {}
      : { [CODEX_POOL_BASE_URL_ENV]: poolBaseUrl }),
    ...(poolAuthToken === undefined
      ? {}
      : { [CODEX_POOL_AUTH_TOKEN_ENV]: poolAuthToken }),
  };
}

function buildAppServerEnv(
  envVars: Readonly<Record<string, string>> | undefined,
): NodeJS.ProcessEnv {
  return withoutBridgeRuntimeEnv(
    sanitizeInheritedChildProcessEnv({
      env: appServerLaunchEnv(envVars),
    }),
  );
}

spawnChildConnection uses this result to create the actual app-server process. Session construction supplies session envVars to that function, and Maintenance children use the same launch path. Model discovery passes model/list envVars into the maintenance path. Therefore the environment is lost after it reaches the provider bridge, not because the probe omitted it or invoked a copied helper.

There is a second, related lifecycle omission. constructionSignature includes the workspace, reasoning/memory/subagent choices and a hashed pool route, but not the selected home:

function constructionSignature(
  cwd: string,
  sessionOptions: CodexSessionOptions,
): string {
  const poolBaseUrl = sessionOptions.envVars?.[CODEX_POOL_BASE_URL_ENV];
  const poolToken = sessionOptions.envVars?.[CODEX_POOL_AUTH_TOKEN_ENV];
  return JSON.stringify({
    cwd,
    reasoningLevel: sessionOptions.reasoningLevel ?? null,
    memoryEnabled: sessionOptions.memoryEnabled ?? null,
    providerSubagentsEnabled: sessionOptions.providerSubagentsEnabled ?? null,
    poolRoute:
      poolBaseUrl === undefined || poolToken === undefined
        ? null
        : {
            baseUrl: poolBaseUrl,
            tokenHash: createHash("sha256").update(poolToken).digest("hex"),
          },
  });
}

function sendThreadDeltas(

requireLiveSessionForTurn compares that signature before deciding whether to rebuild. A home-only change does not trigger replacement. rebuildThreadSession restores by the existing provider thread ID; blindly switching the home during a rebuild would also change the storage/authentication context in which that ID must be found.

History: the selective environment overlay was introduced by trusted commit 5551197af4608e130d518b696d835427b9cfe428, which added pool-aware launches. This explains the pool-specific allowlist; it is not evidence that a general project home override was intentionally supported.

6. Proposed fix and automation safety

Preserve the environment sanitation pipeline and apply a validated effective CODEX_HOME at the child-launch boundary. Treat it consistently for start/resume/fork and maintenance/model discovery without forwarding unrelated project variables. A home-only change must not silently reuse the old child. Before enabling home-based replacement, specify how an existing saved provider session stays bound to its original home, or return an explicit recoverable error when it cannot safely be resumed. Test independent homes, no-override defaults, pool routing, and rollout lookup in the intended home.

No automated PR: changing the selected home changes authentication/configuration and saved-session storage. The simple-fix rule explicitly excludes authentication changes and changes requiring a product/architecture decision. Choosing existing-session home affinity, migration, or refusal semantics is not safe to invent in a narrow launch patch. No production patch, branch, target-repository commit, or push was attempted.

No linked open pull request was present in the issue timeline, and a separate open-PR metadata search for issue 6866 returned none.

7. Verification

The same agent repeated the final reproduction in a second clean detached worktree at the identical trusted base commit. It was clean before copying only the authored test, ran a separate frozen install and scoped build, and then used --force to prevent a cached test result. Each run generated fresh temporary workspaces; no network ports or persistent data stores were needed.

git worktree add --detach ../bb-6866-verify de578a74eef20cc15c2bb68d890e7e9bce55a68e
cd ../bb-6866-verify
git status --porcelain
pnpm install --frozen-lockfile --prefer-offline
pnpm exec turbo run build --filter=bb-plugin-provider-codex
pnpm exec turbo run test --force --filter=bb-plugin-provider-codex -- src/bridge/bridge.home-selection.test.ts

The status command produced no output before the test was copied. Result: exit 1 with the same nine selected-home/lifecycle failures and two passing controls. This is a second clean run by the same agent, not independent verification. No correction to the reported root cause was needed.

   × passes the selected home to thread/start with inherited home true 90ms
   × passes the selected home to thread/start with inherited home false 49ms
   × passes the selected home to thread/resume with inherited home true 58ms
   × passes the selected home to thread/resume with inherited home false 47ms
   × passes the selected home to thread/fork with inherited home true 47ms
   × passes the selected home to thread/fork with inherited home false 47ms
   ✓ preserves the default launch with inherited home true 58ms
   ✓ preserves the default launch with inherited home false 62ms
   × uses the selected home for model discovery 60ms
   × isolates home selection for two concurrently open sessions 109ms
   × does not silently run a turn in the previous home after selection changes 63ms
Expected: "/tmp/bb-home-selection-EXAMPLE/home-b"
Received: "/tmp/bb-home-selection-EXAMPLE/home-a"
 Test Files  1 failed (1)
      Tests  9 failed | 2 passed (11)

Relevant existing launch, session-signature, model-list, and archived-resume suites also pass against unchanged production code, demonstrating the existing coverage gap rather than general bridge breakage:

pnpm exec turbo run test --filter=bb-plugin-provider-codex -- src/bridge/app-server-launch.test.ts src/bridge/bridge.session-signature.test.ts src/bridge/bridge.model-list.test.ts src/bridge/bridge.archived-resume.test.ts

 ✓ |bb-plugin-provider-codex| src/bridge/app-server-launch.test.ts (6 tests) 8ms
 ✓ |bb-plugin-provider-codex| src/bridge/bridge.archived-resume.test.ts (2 tests) 141ms
 ✓ |bb-plugin-provider-codex| src/bridge/bridge.session-signature.test.ts (11 tests) 858ms
 ✓ |bb-plugin-provider-codex| src/bridge/bridge.model-list.test.ts (10 tests) 1317ms
 Test Files  4 passed (4)
      Tests  29 passed (29)

8. Related issues

A small metadata comparison found #4484 (separate Codex AI-service authentication) and #6171 (Account Pool routing isolation). Neither establishes a native non-pooled session-home fix. This report is bounded to the production provider bridge and does not claim those other paths were reproduced.

9. Appendix and limitations

The setup commands, exact test commands, executable test, normalized failure observations, commit-pinned root-cause excerpts, and both run summaries are included above. Both frozen installs and scoped builds succeeded. Tests execute Node child processes locally; no new dependency was added. No real macOS desktop UI, OAuth identity, provider account settings, or Codex rollout lookup was tested. A native authenticated two-project end-to-end run remains follow-up work.

Untrusted-data handling: the issue supplied requested actions and example code. They were treated only as untrusted claims: no issue script, patch, external link, attachment, or linked PR code was executed or fetched. The reproduction was designed from trusted origin/main code and existing repository test fixtures.

> AGENT GENERATED