Compare commits

...
Author SHA1 Message Date
paseo-bot[bot]and3ae3ae 6291549834 Keep Codex thread settings when importing a session (#12167)
* fix(codex): keep thread settings on import

Use the native resume settings for the first imported turn and save
them with the agent so import preserves the thread's choices.

Co-authored-by: 3ae3ae <83870598+3ae3ae@users.noreply.github.com>

* fix(codex): resolve imported Speed for the resumed model

---------

Co-authored-by: paseo-bot[bot] <266920839+paseo-bot[bot]@users.noreply.github.com>
Co-authored-by: 3ae3ae <83870598+3ae3ae@users.noreply.github.com>
2026-12-05 22:42:46 +00:00
2 changed files with 181 additions and 6 deletions
@@ -3954,6 +3954,7 @@ export class CodexAppServerAgentSession implements AgentSession {
private readonly usageSessionKey = randomUUID();
private readonly harnessEnvironment: Record<string, string>;
private readImportedSettings: boolean;
usageSession() {
if (this.closed) return null;
@@ -3977,7 +3978,9 @@ export class CodexAppServerAgentSession implements AgentSession {
private readonly autoReviewEnabled: boolean = false,
private readonly agentId?: string,
private readonly initialResumePurpose: "interactive" | "history" = "interactive",
importOptions?: { readImportedSettings: boolean },
) {
this.readImportedSettings = importOptions?.readImportedSettings ?? false;
this.logger = logger.child({
module: "agent",
provider: CODEX_PROVIDER,
@@ -4098,7 +4101,7 @@ export class CodexAppServerAgentSession implements AgentSession {
this.speedModels =
CodexModelListResponseSchema.parse(await client.request("model/list", {})).data ?? [];
this.normalizeSpeed();
if (!this.readImportedSettings) this.normalizeSpeed();
await this.loadResolvedConfig();
await this.loadCollaborationModes();
await this.loadSkills();
@@ -4106,6 +4109,10 @@ export class CodexAppServerAgentSession implements AgentSession {
if (this.currentThreadId) {
await this.ensureThreadLoaded();
await this.applyDefaultModelAndThinking();
if (this.readImportedSettings) {
this.normalizeSpeed();
this.readImportedSettings = false;
}
}
if (this.closed) {
@@ -4354,7 +4361,7 @@ export class CodexAppServerAgentSession implements AgentSession {
const runs = resolved ?? "default";
this.providerOptions = { ...this.providerOptions, service_tier: runs };
this.requestedServiceTier = runs;
this.openOptionsPatch = { service_tier: runs };
this.openOptionsPatch = { ...this.openOptionsPatch, service_tier: runs };
}
private get serviceTier(): string | null {
@@ -4642,6 +4649,7 @@ export class CodexAppServerAgentSession implements AgentSession {
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
this.rememberRestoredCollaborationMode(response);
this.applyImportedThreadSettings(response);
}
} catch (error) {
const threadId = this.currentThreadId;
@@ -4657,6 +4665,7 @@ export class CodexAppServerAgentSession implements AgentSession {
const response = await this.client.request("thread/resume", params);
this.rememberResolvedSandboxPolicy(response);
this.rememberRestoredCollaborationMode(response);
this.applyImportedThreadSettings(response);
this.logger.info({ threadId }, "Unarchived Codex thread to restore active Paseo agent");
} else {
this.logger.warn({ error, threadId }, "Failed to resume persisted Codex thread");
@@ -4686,6 +4695,26 @@ export class CodexAppServerAgentSession implements AgentSession {
this.refreshResolvedCollaborationMode();
}
private applyImportedThreadSettings(response: unknown): void {
if (!this.readImportedSettings) return;
const thread = toObjectRecord(response);
if (!this.config.model && typeof thread?.model === "string" && thread.model) {
this.config.model = thread.model;
}
if (typeof thread?.reasoningEffort === "string") {
this.config.thinkingOptionId ??= normalizeCodexThinkingOptionId(thread.reasoningEffort);
}
const mode = this.restoredCollaborationMode?.mode;
if (mode === "plan" || mode === "default") {
const planMode = mode === "plan";
this.providerOptions = { ...this.providerOptions, plan_mode: planMode };
this.openOptionsPatch = { ...this.openOptionsPatch, plan_mode: planMode };
this.setPlanMode(planMode);
}
}
private parseSlashCommandInput(text: string): { commandName: string; args?: string } | null {
const trimmed = text.trim();
if (!trimmed.startsWith("/") || trimmed.length <= 1) {
@@ -8610,6 +8639,22 @@ export class CodexAppServerAgentClient implements AgentClient {
launchContext?: AgentLaunchContext,
options?: AgentResumeSessionOptions,
): Promise<AgentSession> {
return this.openResumedSession({ handle, overrides, launchContext, options });
}
private async openResumedSession({
handle,
overrides,
launchContext,
options,
readImportedSettings = false,
}: {
handle: { sessionId: string; metadata?: Record<string, unknown> };
overrides?: Partial<AgentSessionConfig>;
launchContext?: AgentLaunchContext;
options?: AgentResumeSessionOptions;
readImportedSettings?: boolean;
}): Promise<AgentSession> {
const storedConfig = (handle.metadata ?? {}) as Partial<AgentSessionConfig>;
const merged: AgentSessionConfig = {
...storedConfig,
@@ -8641,6 +8686,7 @@ export class CodexAppServerAgentClient implements AgentClient {
autoReviewEnabled,
launchContext?.agentId,
options?.purpose ?? "interactive",
{ readImportedSettings },
);
await session.connect();
return session;
@@ -8706,12 +8752,32 @@ export class CodexAppServerAgentClient implements AgentClient {
}
async importSession(input: ImportProviderSessionInput, context: ImportProviderSessionContext) {
return importSessionFromPersistence({
const imported = await importSessionFromPersistence({
provider: CODEX_PROVIDER,
request: input,
context,
resumeSession: this.resumeSession.bind(this),
resumeSession: (handle, config, launchContext) =>
this.openResumedSession({
handle,
overrides: config,
launchContext,
readImportedSettings: true,
}),
});
try {
const runtime = await imported.session.getRuntimeInfo();
return {
...imported,
config: {
...imported.config,
model: runtime.model ?? imported.config.model,
thinkingOptionId: runtime.thinkingOptionId ?? imported.config.thinkingOptionId,
},
};
} catch (error) {
await imported.session.close();
throw error;
}
}
async getCatalogCacheKey(_options: FetchCatalogOptions): Promise<string> {
@@ -1,14 +1,20 @@
import { mkdtempSync, rmSync } from "node:fs";
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { once } from "node:events";
import { createServer, type Server } from "node:http";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { z } from "zod";
import { afterEach, describe, expect, test } from "vitest";
import { createTestLogger } from "../../../test-utils/test-logger.js";
import { spawnProcess } from "../../../utils/spawn.js";
import { withTimeout } from "../../../utils/promise-timeout.js";
import { CodexAppServerAgentClient, CodexAppServerAgentSession } from "./codex-app-server-agent.js";
import { CodexAppServerClient } from "./codex/app-server-transport.js";
import { DaemonClient } from "../../test-utils/daemon-client.js";
import { createTestPaseoDaemon } from "../../test-utils/paseo-daemon.js";
// Runs the real `codex` binary against a local Responses endpoint standing in
// for a custom provider's OPENAI_BASE_URL, so no login is needed.
@@ -51,10 +57,13 @@ async function startResponsesEndpoint(): Promise<{
baseUrl: string;
server: Server;
requestCount: () => number;
lastRequest: () => unknown;
}> {
let requests = 0;
let lastRequest: unknown;
const server = createServer((req, res) => {
req.resume();
const chunks: Buffer[] = [];
req.on("data", (chunk: Buffer) => chunks.push(chunk));
req.on("end", () => {
if (req.method !== "POST" || req.url !== "/v1/responses") {
res.statusCode = 404;
@@ -62,6 +71,7 @@ async function startResponsesEndpoint(): Promise<{
return;
}
requests += 1;
lastRequest = JSON.parse(Buffer.concat(chunks).toString());
res.setHeader("content-type", "text/event-stream");
res.end(finalAnswer());
});
@@ -74,6 +84,7 @@ async function startResponsesEndpoint(): Promise<{
baseUrl: `http://127.0.0.1:${address.port}/v1`,
server,
requestCount: () => requests,
lastRequest: () => lastRequest,
};
}
@@ -192,3 +203,101 @@ describe("Codex custom provider import list", () => {
120_000,
);
});
async function seedNativePlanThread(cwd: string, env: NodeJS.ProcessEnv): Promise<string> {
const child = await spawnProcess("codex", ["app-server"], { cwd, env, stdio: "pipe" });
const seed = new CodexAppServerClient(child, createTestLogger());
try {
await seed.request("initialize", {
clientInfo: { name: "import-test", version: "1" },
capabilities: { experimentalApi: true },
});
seed.notify("initialized");
const { thread } = z.object({ thread: z.object({ id: z.string() }) }).parse(
await seed.request("thread/start", {
cwd,
model: "gpt-5.4",
config: { model_reasoning_effort: "high" },
}),
);
const completed = Promise.withResolvers<unknown>();
seed.setNotificationHandler((method, params) => {
if (method === "turn/completed") completed.resolve(params);
});
await seed.request("turn/start", {
threadId: thread.id,
input: [{ type: "text", text: "Reply done." }],
collaborationMode: {
mode: "plan",
settings: { model: "gpt-5.4", reasoning_effort: "high", developer_instructions: null },
},
});
expect(
await withTimeout(completed.promise, 15_000, "Native Codex turn did not finish"),
).toMatchObject({ turn: { status: "completed" } });
return thread.id;
} finally {
await seed.dispose();
}
}
test("import preserves the Codex thread model, reasoning effort, and Plan mode", async () => {
const artifacts = fileURLToPath(new URL("../../../../../../.artifacts/", import.meta.url));
mkdirSync(artifacts, { recursive: true });
const cwd = mkdtempSync(path.join(artifacts, "codex-import-settings-"));
const endpoint = await startResponsesEndpoint();
try {
writeFileSync(
path.join(cwd, "config.toml"),
[
'model = "gpt-5.4-mini"',
'model_reasoning_effort = "low"',
'model_provider = "fixture"',
"[model_providers.fixture]",
'name = "Fixture"',
'wire_api = "responses"',
'base_url = "' + endpoint.baseUrl + '"',
].join("\n"),
);
const env = { ...process.env, CODEX_HOME: cwd };
const sessionId = await seedNativePlanThread(cwd, env);
const expectedRequest = { model: "gpt-5.4", reasoning: { effort: "high" } };
expect(endpoint.lastRequest()).toMatchObject(expectedRequest);
const daemon = await createTestPaseoDaemon({
agentClients: {},
providerOverrides: { codex: { env: { CODEX_HOME: cwd }, options: { service_tier: "fast" } } },
paseoHomeRoot: cwd,
});
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
try {
await client.connect();
const agent = await client.importAgent({ provider: "codex", sessionId, cwd });
const previousRequests = endpoint.requestCount();
await client.sendAgentMessage(agent.id, "Reply done again.");
expect(await client.waitForFinish(agent.id, 30_000)).toMatchObject({ status: "idle" });
expect(endpoint.requestCount()).toBeGreaterThan(previousRequests);
expect(endpoint.lastRequest()).toMatchObject(expectedRequest);
expect(agent).toMatchObject({
model: "gpt-5.4",
thinkingOptionId: "high",
runtimeInfo: { extra: { collaborationMode: "Plan" } },
options: { plan_mode: true, service_tier: "default" },
});
await client.setAgentOptions(agent.id, { plan_mode: false });
expect(await client.fetchAgent(agent.id)).toMatchObject({
agent: {
model: "gpt-5.4",
thinkingOptionId: "high",
runtimeInfo: { extra: { collaborationMode: "Default" } },
options: { plan_mode: false, service_tier: "default" },
},
});
} finally {
await client.close();
await daemon.close();
}
} finally {
await closeServer(endpoint.server);
rmSync(cwd, { recursive: true, force: true });
}
}, 60_000);