Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(console): edit a Codex agent's configuration after creation (CHOO-1985) (#213)

Christian McDermottd67ae444f113
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 410229009..f59b115eb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -356,6 +356,30 @@ version of their own to them without also giving them a release of their own.
### [Unreleased]
+#### Added
+- A Codex agent's configuration can now be changed after the agent is created,
+ from the **Advanced configuration** section in its Settings tab — the same
+ section Claude agents already had. Model, reasoning effort and instructions
+ were previously write-once in the add-agent dialog, with no way to edit them
+ (CHOO-1985); **verbosity**, **reasoning summary** and **web search** are newly
+ exposed, and reasoning effort gains `none`. Each option was checked against the
+ Codex binary's own config validation rather than assumed.
+- Leaving one of those fields blank is not the same as choosing its default:
+ blank omits the setting entirely, so your own `~/.codex/config.toml` still
+ decides. That is why the on/off settings offer Default/On/Off rather than a
+ checkbox, which has no way to say "leave it alone".
+- Codex reads these values only when a session starts, so a save applies to the
+ next session. A session already running is named in the section, with a
+ Restart that resumes it on the new configuration. Clearing every field removes
+ the agent's launch profile rather than leaving it orphaned.
+
+#### Changed
+- Advanced configuration is one editor for every provider rather than one per
+ storage mechanism. Providers keep these settings in different places — a
+ repo-agent definition for Claude Code, the launch profile for Codex — and the
+ main process now routes the read and the write, so the difference is no longer
+ visible as the shape of the Settings page.
+
### [0.22.1] - 2026-08-12
#### Changed
diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts
index db3787504..8a49e472b 100644
--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/agent-launch-profile.test.ts
@@ -89,7 +89,7 @@ describe('resolveAgentLaunchProfile', () => {
const profile = resolveAgentLaunchProfile(codexPlugin, {
slug: 'codex-hoot',
workingDir: WD,
- specialization: { model: 'gpt-5.6-terra', reasoningEffort: 'high', instructions: 'be terse' },
+ specialization: { model: 'gpt-5.6-terra', effort: 'high', instructions: 'be terse' },
})!;
expect(profile.files).toHaveLength(1);
expect(profile.files[0].content).toContain('model = "gpt-5.6-terra"');
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts
new file mode 100644
index 000000000..a2017f75b
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-advanced-config.ts
@@ -0,0 +1,76 @@
+import type { RepoAgentAttributes, RepoAgentField } from '@switch-console/core/agents/plugins';
+import { getPlugin } from '@main/core/providers/plugin-registry';
+import {
+ attributesFromProviderConfig,
+ providerConfigFromAttributes,
+} from '@shared/core/agents/agent-provider-config';
+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';
+import { readAgentDefinition, updateAgentDefinition } from './agent-definition';
+import { getAgentById } from './getAgentById';
+import { setAgentProviderConfig } from './setAgentProviderConfig';
+
+/**
+ * An agent's "advanced configuration" — its per-agent model, reasoning effort,
+ * system prompt and whatever else its provider exposes — read and written
+ * without the caller knowing where the provider keeps it.
+ *
+ * There are two places it can live, and they are not interchangeable:
+ * - A **repo-agent definition** on disk (Claude Code: `.claude/agents/<name>.md`),
+ * edited by rewriting the file.
+ * - A **launch profile** built at spawn from the agent row (Codex:
+ * `~/.codex/<name>.config.toml`), edited by writing `providerConfig`.
+ *
+ * Both are per-agent settings collected as the same `RepoAgentField[]` and shown
+ * in the same form, so the storage split is an implementation detail rather than
+ * two features. A provider with neither has no advanced configuration and the
+ * section renders nothing.
+ */
+
+/** The fields this provider exposes, from whichever surface it keeps them in. */
+export function getAgentAdvancedFields(providerId: AgentProviderId): RepoAgentField[] {
+ const behavior = getPlugin(providerId).behavior;
+ const definitionFields = behavior.repoAgents?.attributeFields();
+ if (definitionFields) return definitionFields;
+ return behavior.mcp?.launchProfileFields?.() ?? [];
+}
+
+/**
+ * Current values for the form, or null when there is nothing stored yet — the
+ * caller renders an empty form in that case.
+ */
+export async function readAgentAdvancedConfig(
+ agentId: string
+): Promise<RepoAgentAttributes | null> {
+ const agent = await getAgentById(agentId);
+ if (!agent) throw new Error(`No agent with id ${agentId}`);
+
+ if (getPlugin(agent.providerId).behavior.repoAgents) {
+ return readAgentDefinition(agentId);
+ }
+ return attributesFromProviderConfig(agent.providerConfig);
+}
+
+/**
+ * Save new values. Routed to the provider's own surface: a definition rewrite,
+ * or the agent row plus the side effects a profile change needs (see
+ * {@link setAgentProviderConfig}).
+ */
+export async function updateAgentAdvancedConfig(params: {
+ agentId: string;
+ attributes: RepoAgentAttributes;
+}): Promise<void> {
+ const agent = await getAgentById(params.agentId);
+ if (!agent) throw new Error(`No agent with id ${params.agentId}`);
+
+ const behavior = getPlugin(agent.providerId).behavior;
+ if (behavior.repoAgents) {
+ return updateAgentDefinition(params);
+ }
+ if (!behavior.mcp?.launchProfileFields) {
+ throw new Error(`Agent ${params.agentId} has no editable advanced configuration.`);
+ }
+ return setAgentProviderConfig({
+ agentId: params.agentId,
+ config: providerConfigFromAttributes(params.attributes),
+ });
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
index b90a9e908..ec4e3ebc7 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/controller.ts
@@ -5,6 +5,11 @@ import type { AgentProviderId } from '@shared/core/providers/agent-provider-regi
import type { AgentVerifyResult } from '@shared/core/switch-servers/switch-servers';
import { createRPCController } from '@shared/lib/ipc/rpc';
import { addAgent, type AddAgentParams } from './add-agent';
+import {
+ getAgentAdvancedFields,
+ readAgentAdvancedConfig,
+ updateAgentAdvancedConfig,
+} from './agent-advanced-config';
import { readAgentDefinition, updateAgentDefinition } from './agent-definition';
import { assignAgentServer } from './assignAgentServer';
import {
@@ -28,6 +33,7 @@ import {
setAgentAutoSession,
type AgentAutoSessionParams,
} from './setAgentAutoSession';
+import { setAgentProviderConfig, type AgentProviderConfigParams } from './setAgentProviderConfig';
import { updateAgent, type UpdateAgentParams } from './updateAgent';
export const agentsController = createRPCController({
@@ -38,6 +44,16 @@ export const agentsController = createRPCController({
readAgentDefinition: (params: { agentId: string }) => readAgentDefinition(params.agentId),
updateAgentDefinition: (params: { agentId: string; attributes: RepoAgentAttributes }) =>
updateAgentDefinition(params),
+ /**
+ * The per-agent advanced configuration, wherever the provider keeps it —
+ * a repo-agent definition (Claude) or a launch profile (Codex). One form,
+ * one editor; see `agent-advanced-config.ts`.
+ */
+ advancedFields: (params: { providerId: AgentProviderId }) =>
+ Promise.resolve(getAgentAdvancedFields(params.providerId)),
+ readAdvancedConfig: (params: { agentId: string }) => readAgentAdvancedConfig(params.agentId),
+ updateAdvancedConfig: (params: { agentId: string; attributes: RepoAgentAttributes }) =>
+ updateAgentAdvancedConfig(params),
onboardAgent: (params: OnboardAgentParams) => onboardAgent(params),
onboardLocationAgents: (params: OnboardLocationParams) => onboardLocationAgents(params),
discoverLocationAgents: (params: {
@@ -62,6 +78,8 @@ export const agentsController = createRPCController({
setAgentAutoSession(params),
setAgentAutoApprove: (params: AgentAutoApproveParams): Promise<void> =>
setAgentAutoApprove(params),
+ setAgentProviderConfig: (params: AgentProviderConfigParams): Promise<void> =>
+ setAgentProviderConfig(params),
getAgentAutoSession: (params: { agentId: string }): Promise<boolean> =>
getAgentAutoSession(params),
});
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts
new file mode 100644
index 000000000..3eb277c02
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.test.ts
@@ -0,0 +1,141 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
+
+const updateAgent = vi.fn(
+ async ({ agentId, providerConfig }): Promise<Record<string, unknown> | undefined> => ({
+ id: agentId,
+ name: 'codex.yak',
+ locationId: 'loc-1',
+ providerConfig,
+ })
+);
+const getAgentLocation = vi.fn(async (_agent: unknown) => ({
+ id: 'loc-1',
+ dir: '/repo',
+ sshHost: null,
+}));
+const getRemoteAgentLocation = vi.fn();
+const listAutoSessionAgentIds = vi.fn();
+const ensureRemoteWatcher = vi.fn(async (_id: string) => {});
+const removeAgentLaunchProfile = vi.fn(
+ async (_agent: unknown, _location: unknown, _slug: string) => {}
+);
+const getAgentById = vi.fn(
+ async (agentId: string): Promise<Record<string, unknown> | undefined> => ({
+ id: agentId,
+ name: 'codex.yak',
+ locationId: 'loc-1',
+ })
+);
+
+vi.mock('./getAgentById', () => ({ getAgentById: (id: string) => getAgentById(id) }));
+vi.mock('./updateAgent', () => ({ updateAgent: (p: unknown) => updateAgent(p) }));
+vi.mock('./agent-location', () => ({
+ getAgentLocation: (a: unknown) => getAgentLocation(a),
+ getRemoteAgentLocation: (a: unknown) => getRemoteAgentLocation(a),
+}));
+vi.mock('@main/core/switch-rooms/auto-session-store', () => ({
+ listAutoSessionAgentIds: () => listAutoSessionAgentIds(),
+}));
+vi.mock('./remote-watcher', () => ({
+ ensureRemoteWatcher: (id: string) => ensureRemoteWatcher(id),
+}));
+vi.mock('./remove-launch-profile', () => ({
+ removeAgentLaunchProfile: (agent: unknown, location: unknown, slug: string) =>
+ removeAgentLaunchProfile(agent, location, slug),
+}));
+
+import { setAgentProviderConfig } from './setAgentProviderConfig';
+
+const CONFIG: AgentProviderConfig = { version: '1', model: 'gpt-5.6-terra', effort: 'high' };
+
+describe('setAgentProviderConfig', () => {
+ beforeEach(() => {
+ updateAgent.mockClear();
+ getAgentById.mockClear();
+ getAgentById.mockResolvedValue({ id: 'agent-1', name: 'codex.yak', locationId: 'loc-1' });
+ getAgentLocation.mockClear();
+ getRemoteAgentLocation.mockReset();
+ listAutoSessionAgentIds.mockReset();
+ ensureRemoteWatcher.mockClear();
+ removeAgentLaunchProfile.mockClear();
+ });
+
+ it('writes the config to the agent row', async () => {
+ getRemoteAgentLocation.mockResolvedValue(null);
+
+ await setAgentProviderConfig({ agentId: 'agent-1', config: CONFIG });
+
+ expect(updateAgent).toHaveBeenCalledWith({ agentId: 'agent-1', providerConfig: CONFIG });
+ });
+
+ it('leaves a local agent alone otherwise — the profile is rewritten at the next spawn', async () => {
+ getRemoteAgentLocation.mockResolvedValue(null);
+
+ await setAgentProviderConfig({ agentId: 'agent-1', config: CONFIG });
+
+ expect(ensureRemoteWatcher).not.toHaveBeenCalled();
+ expect(removeAgentLaunchProfile).not.toHaveBeenCalled();
+ });
+
+ it('removes the launch profile when the config is cleared, so no orphan is left behind', async () => {
+ getRemoteAgentLocation.mockResolvedValue(null);
+
+ await setAgentProviderConfig({ agentId: 'agent-1', config: null });
+
+ expect(updateAgent).toHaveBeenCalledWith({ agentId: 'agent-1', providerConfig: null });
+ expect(removeAgentLaunchProfile).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'agent-1' }),
+ expect.objectContaining({ dir: '/repo' }),
+ 'codex.yak'
+ );
+ });
+
+ it('re-pushes the spec to a remote agent whose watcher is running (auto_session on)', async () => {
+ getRemoteAgentLocation.mockResolvedValue({ id: 'loc-1', sshHost: 'vm' });
+ listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
+
+ await setAgentProviderConfig({ agentId: 'agent-1', config: CONFIG });
+
+ expect(ensureRemoteWatcher).toHaveBeenCalledWith('agent-1');
+ });
+
+ it('skips the re-push for a remote agent with auto_session off (nothing running to refresh)', async () => {
+ getRemoteAgentLocation.mockResolvedValue({ id: 'loc-1', sshHost: 'vm' });
+ listAutoSessionAgentIds.mockResolvedValue([]);
+
+ await setAgentProviderConfig({ agentId: 'agent-1', config: CONFIG });
+
+ expect(ensureRemoteWatcher).not.toHaveBeenCalled();
+ });
+
+ it('surfaces an unreachable VM rather than reporting a save that only half landed', async () => {
+ getRemoteAgentLocation.mockResolvedValue({ id: 'loc-1', sshHost: 'vm' });
+ listAutoSessionAgentIds.mockResolvedValue(['agent-1']);
+ ensureRemoteWatcher.mockRejectedValueOnce(new Error('ssh: connect failed'));
+
+ await expect(setAgentProviderConfig({ agentId: 'agent-1', config: CONFIG })).rejects.toThrow(
+ /ssh: connect failed/
+ );
+ });
+
+ it('throws when the agent does not exist', async () => {
+ getAgentById.mockResolvedValueOnce(undefined);
+
+ await expect(setAgentProviderConfig({ agentId: 'ghost', config: CONFIG })).rejects.toThrow(
+ /No agent with id ghost/
+ );
+ expect(updateAgent).not.toHaveBeenCalled();
+ });
+
+ it('does not write the row when clearing but the location cannot be resolved', async () => {
+ getAgentLocation.mockRejectedValueOnce(new Error('Location loc-1 not found'));
+
+ await expect(setAgentProviderConfig({ agentId: 'agent-1', config: null })).rejects.toThrow(
+ /Location loc-1 not found/
+ );
+ // Reporting a failed save while the change had already landed is the trap
+ // this ordering exists to avoid.
+ expect(updateAgent).not.toHaveBeenCalled();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.ts b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.ts
new file mode 100644
index 000000000..34fccb749
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/agents/setAgentProviderConfig.ts
@@ -0,0 +1,58 @@
+import { listAutoSessionAgentIds } from '@main/core/switch-rooms/auto-session-store';
+import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
+import { getAgentLocation, getRemoteAgentLocation } from './agent-location';
+import { getAgentById } from './getAgentById';
+import { ensureRemoteWatcher } from './remote-watcher';
+import { removeAgentLaunchProfile } from './remove-launch-profile';
+import { updateAgent } from './updateAgent';
+
+export type AgentProviderConfigParams = {
+ agentId: string;
+ /** Null clears the specialization, putting the agent back on provider defaults. */
+ config: AgentProviderConfig | null;
+};
+
+/**
+ * Set an agent's per-agent provider config (Codex model / reasoning effort /
+ * instructions) after creation.
+ *
+ * The value is folded into the agent's launch profile when a session starts, so
+ * a change reaches the *next* session rather than any that is already running —
+ * the profile is read by the CLI at spawn and there is no way to reload it under
+ * a live process. Callers that want it applied now restart the session
+ * (`sessions.restartAgent`).
+ *
+ * Two things have to happen beyond the row write for that to hold:
+ * - Clearing the config removes the launch profile. With nothing to specialize
+ * the next launch passes no `--profile` at all, so the file would otherwise be
+ * left behind unreferenced — and would come back to life the moment the agent
+ * is specialized again under the same name and directory.
+ * - A remote agent bakes the specialization into its on-VM watcher's launch
+ * spec, so the watcher is re-ensured to rewrite it; the running sidecar
+ * re-reads the spec and applies it to the next auto-started session. When
+ * auto_session is off there is no watcher to refresh and the next
+ * `ensureRemoteWatcher` picks the value up.
+ *
+ * The re-ensure is allowed to throw: if the VM is unreachable the change cannot
+ * reach auto-started sessions, and the caller should surface that rather than
+ * report a save that only half landed.
+ */
+export async function setAgentProviderConfig(params: AgentProviderConfigParams): Promise<void> {
+ // Resolve the location before writing, not after. It is only needed to clear,
+ // but a missing location row would otherwise throw with the change already
+ // committed — telling the caller the save failed when it had not.
+ const existing = await getAgentById(params.agentId);
+ if (!existing) throw new Error(`No agent with id ${params.agentId}`);
+ const location = params.config === null ? await getAgentLocation(existing) : null;
+
+ const agent = await updateAgent({ agentId: params.agentId, providerConfig: params.config });
+ if (!agent) throw new Error(`No agent with id ${params.agentId}`);
+
+ if (location) {
+ await removeAgentLaunchProfile(agent, location, agent.name ?? agent.id);
+ }
+
+ if ((await getRemoteAgentLocation(agent)) === null) return;
+ if (!(await listAutoSessionAgentIds()).includes(agent.id)) return;
+ await ensureRemoteWatcher(agent.id);
+}
diff --git a/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts b/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts
index db2fe0b3f..89073bec4 100644
--- a/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts
+++ b/console/apps/switch-console-desktop/src/main/core/agents/updateAgent.ts
@@ -1,6 +1,7 @@
import { eq, sql } from 'drizzle-orm';
import { db } from '@main/db/client';
import { agents } from '@main/db/schema';
+import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
import type { Agent } from '@shared/core/agents/agents';
import { agentEvents } from './agent-events';
import { mapAgentRowToAgent } from './utils';
@@ -12,6 +13,8 @@ export type UpdateAgentParams = {
apiEndpoint?: string | null;
serverId?: string;
autoApprove?: boolean;
+ /** Null clears the agent's specialization, putting it back on provider defaults. */
+ providerConfig?: AgentProviderConfig | null;
};
type AgentUpdateSet = Parameters<ReturnType<typeof db.update<typeof agents>>['set']>[0];
@@ -23,6 +26,7 @@ export async function updateAgent(params: UpdateAgentParams): Promise<Agent | un
if (params.apiEndpoint !== undefined) set.apiEndpoint = params.apiEndpoint;
if (params.serverId !== undefined) set.serverId = params.serverId;
if (params.autoApprove !== undefined) set.autoApprove = params.autoApprove;
+ if (params.providerConfig !== undefined) set.providerConfig = params.providerConfig;
const [row] = await db.update(agents).set(set).where(eq(agents.id, params.agentId)).returning();
if (!row) return undefined;
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/controller.ts b/console/apps/switch-console-desktop/src/main/core/sessions/controller.ts
index 97863ee6c..fba10a5f4 100644
--- a/console/apps/switch-console-desktop/src/main/core/sessions/controller.ts
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/controller.ts
@@ -6,6 +6,7 @@ import { dehydrateSession } from './operations/dehydrateSession';
import { getSession } from './operations/getSession';
import { hydrateSession } from './operations/hydrateSession';
import { markSessionSeen } from './operations/markSessionSeen';
+import { restartSessionAgent } from './operations/restartSessionAgent';
import { sessionService } from './session-service';
export const sessionController = createRPCController({
@@ -64,6 +65,13 @@ export const sessionController = createRPCController({
async stopAgent(sessionId: string) {
return sessionService.stopAgent(sessionId);
},
+ /**
+ * Restart a session's agent process in place, so a setting only read at spawn
+ * (the Codex launch profile) reaches a session that is already running.
+ */
+ async restartAgent(sessionId: string) {
+ return restartSessionAgent(sessionId);
+ },
async provisionSession(sessionId: string) {
return sessionService.provisionSession(sessionId);
},
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/operations/restartSessionAgent.test.ts b/console/apps/switch-console-desktop/src/main/core/sessions/operations/restartSessionAgent.test.ts
new file mode 100644
index 000000000..689635a1d
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/operations/restartSessionAgent.test.ts
@@ -0,0 +1,130 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const resolveSessionAgent = vi.fn();
+const loadSessionWithAgent = vi.fn();
+const mapSessionRowToSession = vi.fn(
+ (_row: unknown, _providerId: unknown, _name: unknown): Record<string, unknown> => ({
+ id: 'session-1',
+ title: 'A session',
+ providerSessionId: 'rollout-abc',
+ })
+);
+const isAttachableRuntime = vi.fn((_runtime: unknown) => false);
+const requestAttach = vi.fn(async (_id: string, _reason: string) => 'attached');
+
+vi.mock('../../locations/utils', () => ({
+ resolveSessionAgent: (id: string) => resolveSessionAgent(id),
+}));
+vi.mock('../session-join', () => ({
+ loadSessionWithAgent: (id: string) => loadSessionWithAgent(id),
+}));
+vi.mock('../utils/utils', () => ({
+ mapSessionRowToSession: (row: unknown, providerId: unknown, name: unknown) =>
+ mapSessionRowToSession(row, providerId, name),
+}));
+vi.mock('@main/core/agent-runtime/attachment/types', () => ({
+ isAttachableRuntime: (runtime: unknown) => isAttachableRuntime(runtime),
+}));
+vi.mock('@main/core/agent-runtime/attachment/production-remote-attachment-pool', () => ({
+ remoteAttachmentPool: {
+ requestAttach: (id: string, reason: string) => requestAttach(id, reason),
+ },
+}));
+
+import { restartSessionAgent } from './restartSessionAgent';
+
+function makeAgent() {
+ const calls: string[] = [];
+ return {
+ calls,
+ stop: vi.fn(async () => {
+ calls.push('stop');
+ }),
+ start: vi.fn(async () => {
+ calls.push('start');
+ }),
+ };
+}
+
+describe('restartSessionAgent', () => {
+ beforeEach(() => {
+ resolveSessionAgent.mockReset();
+ loadSessionWithAgent.mockReset();
+ mapSessionRowToSession.mockClear();
+ mapSessionRowToSession.mockReturnValue({
+ id: 'session-1',
+ title: 'A session',
+ providerSessionId: 'rollout-abc',
+ });
+ isAttachableRuntime.mockReset();
+ isAttachableRuntime.mockReturnValue(false);
+ requestAttach.mockClear();
+ loadSessionWithAgent.mockResolvedValue({ row: {}, providerId: 'codex', name: 'codex.yak' });
+ });
+
+ it('stops the agent before starting it again, so the new profile is read at spawn', async () => {
+ const agent = makeAgent();
+ resolveSessionAgent.mockReturnValue(agent);
+
+ await restartSessionAgent('session-1');
+
+ expect(agent.calls).toEqual(['stop', 'start']);
+ });
+
+ it('resumes rather than starting fresh, so the conversation survives the restart', async () => {
+ const agent = makeAgent();
+ resolveSessionAgent.mockReturnValue(agent);
+
+ await restartSessionAgent('session-1');
+
+ expect(agent.start).toHaveBeenCalledWith(
+ expect.objectContaining({ id: 'session-1' }),
+ undefined,
+ true
+ );
+ });
+
+ it('reconciles the attachment pool for a remote runtime, which comes back attached', async () => {
+ const agent = makeAgent();
+ resolveSessionAgent.mockReturnValue(agent);
+ isAttachableRuntime.mockReturnValue(true);
+
+ await restartSessionAgent('session-1');
+
+ expect(requestAttach).toHaveBeenCalledWith('session-1', 'user');
+ });
+
+ it('leaves the attachment pool alone for a local runtime, which never registers', async () => {
+ const agent = makeAgent();
+ resolveSessionAgent.mockReturnValue(agent);
+
+ await restartSessionAgent('session-1');
+
+ expect(requestAttach).not.toHaveBeenCalled();
+ });
+
+ it('throws when the session has no running agent to restart', async () => {
+ resolveSessionAgent.mockReturnValue(null);
+
+ await expect(restartSessionAgent('session-1')).rejects.toThrow(/no running agent/);
+ });
+
+ it('refuses a session that never started a conversation rather than silently starting a new one', async () => {
+ const agent = makeAgent();
+ resolveSessionAgent.mockReturnValue(agent);
+ mapSessionRowToSession.mockReturnValue({ id: 'session-1', title: 'A session' });
+
+ await expect(restartSessionAgent('session-1')).rejects.toThrow(
+ /has not started a conversation/
+ );
+ expect(agent.stop).not.toHaveBeenCalled();
+ expect(agent.start).not.toHaveBeenCalled();
+ });
+
+ it('throws when the session row is gone', async () => {
+ resolveSessionAgent.mockReturnValue(makeAgent());
+ loadSessionWithAgent.mockResolvedValue(null);
+
+ await expect(restartSessionAgent('session-1')).rejects.toThrow(/Session row not found/);
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/operations/restartSessionAgent.ts b/console/apps/switch-console-desktop/src/main/core/sessions/operations/restartSessionAgent.ts
new file mode 100644
index 000000000..a53c56090
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/main/core/sessions/operations/restartSessionAgent.ts
@@ -0,0 +1,51 @@
+import { remoteAttachmentPool } from '@main/core/agent-runtime/attachment/production-remote-attachment-pool';
+import { isAttachableRuntime } from '@main/core/agent-runtime/attachment/types';
+import { resolveSessionAgent } from '../../locations/utils';
+import { loadSessionWithAgent } from '../session-join';
+import { mapSessionRowToSession } from '../utils/utils';
+
+/**
+ * Stop a session's agent process and start it again in place.
+ *
+ * This is how a per-agent setting that is only read at spawn — the Codex launch
+ * profile's model, reasoning effort and instructions — reaches a session that is
+ * already running. Nothing else re-reads it: the CLI parses its profile once, at
+ * startup.
+ *
+ * The restart resumes rather than starting a fresh conversation, so the session
+ * keeps its history and picks up the new profile; `codex resume` is specialized
+ * by the same profile as a first launch. The session row is untouched — the
+ * session stays provisioned throughout and only its agent process is replaced.
+ *
+ * A remote runtime comes back with a terminal open, because `start` spawns one.
+ * The attachment pool caches an attach state per session and is not on this
+ * path, so it is told: restarting a *detached* session would otherwise leave it
+ * reported as detached while a terminal is in fact open. When the runtime is
+ * already attached this only reconciles that cached state.
+ */
+export async function restartSessionAgent(sessionId: string): Promise<void> {
+ const agent = resolveSessionAgent(sessionId);
+ if (!agent) throw new Error(`Session ${sessionId} has no running agent to restart`);
+
+ const loaded = await loadSessionWithAgent(sessionId);
+ if (!loaded) throw new Error(`Session row not found for ${sessionId}`);
+
+ const session = mapSessionRowToSession(loaded.row, loaded.providerId, loaded.name);
+
+ // Without a provider-native session id there is no conversation to resume, and
+ // `resolveAgentSessionCommandArgs` quietly downgrades a Codex resume to a fresh
+ // start. Refuse instead: a session that never launched its agent has nothing
+ // running on the old configuration, and will pick up the new one by itself.
+ if (!session.providerSessionId) {
+ throw new Error(
+ `Session ${sessionId} has not started a conversation yet — its next launch already uses the current configuration.`
+ );
+ }
+
+ await agent.stop();
+ await agent.start(session, undefined, true);
+
+ if (isAttachableRuntime(agent)) {
+ await remoteAttachmentPool.requestAttach(sessionId, 'user');
+ }
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx
index bf1da9c95..26a14be08 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/codex-agent-config.tsx
@@ -1,9 +1,13 @@
-import type { RepoAgentField } from '@switch-console/core/agents/plugins';
+import { useQuery } from '@tanstack/react-query';
import { ChevronRight } from 'lucide-react';
-import { useCallback, useEffect, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import { rpc } from '@renderer/lib/ipc';
import { Field, FieldDescription, FieldLabel } from '@renderer/lib/ui/field';
import { cn } from '@renderer/utils/utils';
-import type { AgentProviderConfig } from '@shared/core/agents/agent-provider-config';
+import {
+ type AgentProviderConfig,
+ providerConfigFromAttributes,
+} from '@shared/core/agents/agent-provider-config';
import {
attributesFromForm,
DefinitionFieldInput,
@@ -12,63 +16,13 @@ import {
type FormValue,
} from '../agent-definition-fields';
-/**
- * Per-agent Codex configuration for the add-agent modal. Codex has no repo-agent
- * definition surface (so {@link AgentAdvancedConfig} renders nothing for it);
- * instead Switch Console folds these values into the agent's Codex profile at launch.
- *
- * Effort levels mirror `CODEX_REASONING_EFFORTS` in the codex plugin — kept small
- * and stable there, duplicated here so the renderer needs no plugin import.
- * Model is free text because the Codex model catalog changes over time; blank
- * fields leave the user's base `~/.codex/config.toml` default in place.
- */
-const CODEX_CONFIG_FIELDS: RepoAgentField[] = [
- {
- key: 'model',
- label: 'Model',
- type: 'text',
- placeholder: 'e.g. gpt-5.6-terra — blank uses the Codex default',
- help: 'Overrides the model for this agent only.',
- },
- {
- key: 'effort',
- label: 'Reasoning effort',
- type: 'select',
- options: [
- { value: '', label: 'Default' },
- { value: 'low', label: 'low' },
- { value: 'medium', label: 'medium' },
- { value: 'high', label: 'high' },
- { value: 'xhigh', label: 'xhigh' },
- { value: 'max', label: 'max' },
- ],
- },
- {
- key: 'instructions',
- label: 'Instructions',
- type: 'textarea',
- placeholder: "A system prompt for this agent, e.g. 'You are a careful reviewer…'",
- help: "Added to Codex's own instructions as extra developer guidance. Blank keeps Codex defaults.",
- },
-];
-
-function toProviderConfig(state: FormState): AgentProviderConfig | null {
- const attrs = attributesFromForm(CODEX_CONFIG_FIELDS, state);
- const str = (value: unknown): string | undefined => {
- const trimmed = typeof value === 'string' ? value.trim() : '';
- return trimmed ? trimmed : undefined;
- };
- const model = str(attrs.model);
- const effort = str(attrs.effort);
- const instructions = str(attrs.instructions);
- if (!model && !effort && !instructions) return null;
- return { version: '1', model, effort, instructions };
-}
-
/**
* Collapsed "Codex configuration" section. Reports the assembled per-agent
* provider config (or null when nothing is set) so the modal can pass it to
* `addAgent`, which persists it on the agent and folds it into the launch profile.
+ *
+ * The fields are the same ones the agent's Settings tab edits after creation —
+ * fetched over RPC from the codex plugin, so the two forms cannot drift.
*/
export function CodexAgentConfig({
onChange,
@@ -76,16 +30,28 @@ export function CodexAgentConfig({
onChange: (config: AgentProviderConfig | null) => void;
}) {
const [open, setOpen] = useState(false);
- const [state, setState] = useState<FormState>(() => emptyForm(CODEX_CONFIG_FIELDS));
+ const { data } = useQuery({
+ queryKey: ['agentAdvancedFields', 'codex'],
+ queryFn: () => rpc.agents.advancedFields({ providerId: 'codex' }),
+ });
+ const fields = useMemo(() => data ?? [], [data]);
+
+ const [state, setState] = useState<FormState>({});
useEffect(() => {
- onChange(toProviderConfig(state));
- }, [state, onChange]);
+ setState(emptyForm(fields));
+ }, [fields]);
+
+ useEffect(() => {
+ onChange(providerConfigFromAttributes(attributesFromForm(fields, state)));
+ }, [fields, state, onChange]);
const setField = useCallback((key: string, value: FormValue) => {
setState((prev) => ({ ...prev, [key]: value }));
}, []);
+ if (fields.length === 0) return null;
+
return (
<div className="rounded-md border border-border">
<button
@@ -98,7 +64,7 @@ export function CodexAgentConfig({
</button>
{open && (
<div className="flex flex-col gap-4 border-t border-border px-3 py-3">
- {CODEX_CONFIG_FIELDS.map((field) => (
+ {fields.map((field) => (
<Field key={field.key}>
<FieldLabel htmlFor={`codex-config-${field.key}`}>
{field.label} (optional)
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx
new file mode 100644
index 000000000..828028b75
--- /dev/null
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section.tsx
@@ -0,0 +1,250 @@
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+import { Loader2, RefreshCw } from 'lucide-react';
+import { observer } from 'mobx-react-lite';
+import { useEffect, useMemo, useState } from 'react';
+import {
+ advancedFields,
+ attributesFromForm,
+ DefinitionFieldInput,
+ emptyForm,
+ formFromAttributes,
+ type FormState,
+ type FormValue,
+} from '@renderer/features/locations/components/agent-definition-fields';
+import { getSessionManagerStore } from '@renderer/features/sessions/stores/session-selectors';
+import { isProvisioned } from '@renderer/features/sessions/stores/session-store';
+import { toast } from '@renderer/lib/hooks/use-toast';
+import { rpc } from '@renderer/lib/ipc';
+import { Button } from '@renderer/lib/ui/button';
+import { Field, FieldDescription, FieldLabel, FieldTitle } from '@renderer/lib/ui/field';
+import { log } from '@renderer/utils/logger';
+
+/**
+ * Per-agent "Advanced configuration" in the Settings tab: the model, reasoning
+ * effort, tools and system prompt for an existing agent.
+ *
+ * Providers keep these in different places — Claude Code in the repo-agent
+ * definition it launches by name, Codex in the profile it loads at startup —
+ * but they are the same settings collected as the same fields, so this is one
+ * section for both. The main process routes the read and the write to whichever
+ * surface the provider actually uses (`agent-advanced-config.ts`); the agent
+ * name is immutable either way, so only advanced attributes are editable here
+ * (CHOO-1440, CHOO-1985).
+ */
+export const AgentAdvancedSettingsSection = observer(function AgentAdvancedSettingsSection({
+ locationId,
+ agentId,
+}: {
+ locationId: string;
+ agentId: string | undefined;
+}) {
+ const queryClient = useQueryClient();
+
+ const { data: agents } = useQuery({
+ queryKey: ['location-agents', locationId],
+ queryFn: () => rpc.agents.getAgents(locationId),
+ });
+ const agent = (agents ?? []).find((a) => a.id === agentId);
+ const providerId = agent?.providerId ?? null;
+ const editable = !!agent;
+
+ const { data: allFields } = useQuery({
+ queryKey: ['agentAdvancedFields', providerId],
+ queryFn: () => (providerId ? rpc.agents.advancedFields({ providerId }) : Promise.resolve([])),
+ enabled: !!providerId,
+ });
+ const fields = useMemo(() => advancedFields(allFields ?? []), [allFields]);
+
+ const { data: current } = useQuery({
+ queryKey: ['agent-advanced-config', agentId],
+ queryFn: () => (agentId ? rpc.agents.readAdvancedConfig({ agentId }) : Promise.resolve(null)),
+ enabled: !!agentId && editable,
+ });
+
+ const savedForm = useMemo(
+ () => (current ? formFromAttributes(fields, current) : emptyForm(fields)),
+ [fields, current]
+ );
+
+ const [form, setForm] = useState<FormState>({});
+ // Seed (and re-seed after save/agent change) from the persisted values. During
+ // editing no refetch fires, so local edits are preserved until Save.
+ useEffect(() => {
+ setForm(savedForm);
+ }, [savedForm]);
+
+ const staleSessionIds = sessionsStartedBeforeChanges(locationId, agentId);
+
+ const save = useMutation({
+ mutationFn: () =>
+ rpc.agents.updateAdvancedConfig({
+ agentId: agentId as string,
+ attributes: attributesFromForm(fields, form),
+ }),
+ onSuccess: () => {
+ toast({ title: 'Advanced configuration saved' });
+ void queryClient.invalidateQueries({ queryKey: ['agent-advanced-config', agentId] });
+ void queryClient.invalidateQueries({ queryKey: ['location-agents', locationId] });
+ },
+ onError: (error) => {
+ log.error('Failed to save agent advanced configuration', { agentId, error });
+ toast({
+ title: 'Failed to save configuration',
+ description: String(error),
+ variant: 'destructive',
+ });
+ // A save can fail after the row was written — pushing the change to a
+ // remote host is a separate step that can fail on its own. Re-read rather
+ // than leave the form showing values that are no longer what is stored.
+ void queryClient.invalidateQueries({ queryKey: ['agent-advanced-config', agentId] });
+ void queryClient.invalidateQueries({ queryKey: ['location-agents', locationId] });
+ },
+ });
+
+ // The Settings page swaps agents in place rather than remounting, so a save on
+ // the previous agent must not leave its restart notice over the next one.
+ const resetSave = save.reset;
+ useEffect(() => {
+ resetSave();
+ }, [agentId, resetSave]);
+
+ const [restartFailed, setRestartFailed] = useState<string[]>([]);
+ const restart = useMutation({
+ mutationFn: async () => {
+ // Restart the ones that have not already been restarted: a retry after a
+ // partial failure must not kill and respawn the sessions that succeeded.
+ const targets = restartFailed.length > 0 ? restartFailed : staleSessionIds;
+ const results = await Promise.allSettled(
+ targets.map((sessionId) => rpc.sessions.restartAgent(sessionId))
+ );
+ const failed = targets.filter((_, i) => results[i]?.status === 'rejected');
+ setRestartFailed(failed);
+ if (failed.length > 0) {
+ const reasons = results
+ .filter((r): r is PromiseRejectedResult => r.status === 'rejected')
+ .map((r) => String(r.reason));
+ throw new Error(`${failed.length} of ${targets.length} failed — ${reasons.join('; ')}`);
+ }
+ },
+ onSuccess: () => {
+ toast({ title: 'Session restarted on the new configuration' });
+ // Everything running now carries the saved values.
+ save.reset();
+ },
+ onError: (error) => {
+ log.error('Failed to restart a session after an advanced configuration change', {
+ agentId,
+ error,
+ });
+ toast({
+ title: 'Failed to restart the session',
+ description: String(error),
+ variant: 'destructive',
+ });
+ },
+ });
+
+ if (!editable || fields.length === 0) return null;
+
+ const dirty =
+ JSON.stringify(attributesFromForm(fields, form)) !==
+ JSON.stringify(attributesFromForm(fields, savedForm));
+
+ const setField = (key: string, value: FormValue) =>
+ setForm((prev) => ({ ...prev, [key]: value }));
+
+ // Only Codex is offered a restart here. Its profile is provably read once, at
+ // spawn, and its resume is verified to carry the new profile. Claude reads its
+ // definition at launch too and very likely wants the same treatment, but that
+ // is a change to Claude's behaviour and is being raised on its own.
+ const restartable = providerId === 'codex';
+ const showStaleNotice = restartable && staleSessionIds.length > 0 && (dirty || save.isSuccess);
+
+ return (
+ <Field>
+ <FieldTitle>Advanced configuration</FieldTitle>
+ <FieldDescription className="text-foreground-muted">
+ The agent&apos;s model, reasoning effort, tools, and system prompt. The agent name is fixed.
+ </FieldDescription>
+ <div className="flex flex-col gap-4 rounded-md border border-border px-3 py-3">
+ {fields.map((field) => (
+ <Field key={field.key}>
+ <FieldLabel htmlFor={`agent-advanced-${field.key}`}>
+ {field.label}
+ {field.required || field.type === 'boolean' ? '' : ' (optional)'}
+ </FieldLabel>
+ <DefinitionFieldInput
+ field={field}
+ value={form[field.key] ?? (field.type === 'boolean' ? false : '')}
+ onChange={(value) => setField(field.key, value)}
+ />
+ {field.help && (
+ <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>
+ )}
+ </Field>
+ ))}
+ <div className="flex justify-end">
+ <Button
+ type="button"
+ size="sm"
+ disabled={!dirty || save.isPending}
+ onClick={() => save.mutate()}
+ >
+ {save.isPending ? 'Saving...' : 'Save'}
+ </Button>
+ </div>
+
+ {showStaleNotice && (
+ <div className="flex flex-wrap items-center justify-between gap-2 border-t border-border pt-3">
+ <p className="text-xs text-foreground-muted">
+ {staleSessionIds.length === 1
+ ? 'A session is running'
+ : `${staleSessionIds.length} sessions are running`}{' '}
+ on the previous configuration — Codex reads this only when a session starts.{' '}
+ {dirty
+ ? 'Save, then Restart to apply it now.'
+ : 'It applies to the next session — or use Restart to apply it now (the conversation is resumed).'}
+ </p>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={dirty || restart.isPending}
+ onClick={() => restart.mutate()}
+ >
+ {restart.isPending ? (
+ <Loader2 className="size-3.5 animate-spin" />
+ ) : (
+ <RefreshCw className="size-3.5" />
+ )}
+ {restartFailed.length > 0 ? 'Retry restart' : 'Restart'}
+ </Button>
+ </div>
+ )}
+ </div>
+ </Field>
+ );
+});
+
+/**
+ * The agent's sessions that already started a conversation, and so are running
+ * on whatever configuration was in place at the time.
+ *
+ * `providerSessionId` is the test rather than "is provisioned": a remote session
+ * is provisioned at creation so it can carry room traffic, but its agent process
+ * is only launched when the terminal is first opened. Counting those would claim
+ * a running session that does not exist — and restarting one cannot resume a
+ * conversation that never started. Read from the session store rather than
+ * queried, so it tracks sessions coming and going; call only from an `observer`.
+ */
+function sessionsStartedBeforeChanges(locationId: string, agentId: string | undefined): string[] {
+ const manager = getSessionManagerStore(locationId);
+ if (!manager || !agentId) return [];
+ return [...manager.sessions.values()]
+ .filter(
+ (session) =>
+ isProvisioned(session) &&
+ session.data.agentId === agentId &&
+ !!session.data.providerSessionId
+ )
+ .map((session) => session.data.id);
+}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsx
deleted file mode 100644
index 27e13abbc..000000000
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/sections/agent-definition-settings-section.tsx
+++ /dev/null
@@ -1,132 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
-import { useEffect, useMemo, useState } from 'react';
-import {
- advancedFields,
- attributesFromForm,
- DefinitionFieldInput,
- emptyForm,
- formFromAttributes,
- type FormState,
- type FormValue,
-} from '@renderer/features/locations/components/agent-definition-fields';
-import { toast } from '@renderer/lib/hooks/use-toast';
-import { rpc } from '@renderer/lib/ipc';
-import { Button } from '@renderer/lib/ui/button';
-import { Field, FieldDescription, FieldLabel, FieldTitle } from '@renderer/lib/ui/field';
-import { log } from '@renderer/utils/logger';
-
-/**
- * Per-agent "Advanced configuration" editor in the Settings tab: the provider's
- * definition attributes (model, effort, tools, system prompt, …) for an existing
- * agent, prefilled from its on-disk definition and saved back by rewriting it
- * (`.claude/agents/<name>.md`). The name is immutable — it is the agent's
- * identity — so only advanced attributes are editable here (CHOO-1440).
- */
-export function AgentDefinitionSettingsSection({
- locationId,
- agentId,
-}: {
- locationId: string;
- agentId: string | undefined;
-}) {
- const { data: agents } = useQuery({
- queryKey: ['location-agents', locationId],
- queryFn: () => rpc.agents.getAgents(locationId),
- });
- const agent = (agents ?? []).find((a) => a.id === agentId);
- const providerId = agent?.providerId ?? null;
- const editable = !!agent;
-
- const { data: allFields } = useQuery({
- queryKey: ['agentDefinitionFields', providerId],
- queryFn: () => (providerId ? rpc.agents.definitionFields({ providerId }) : Promise.resolve([])),
- enabled: !!providerId,
- });
- const fields = useMemo(() => advancedFields(allFields ?? []), [allFields]);
-
- const { data: current } = useQuery({
- queryKey: ['agent-definition', agentId],
- queryFn: () => (agentId ? rpc.agents.readAgentDefinition({ agentId }) : Promise.resolve(null)),
- enabled: !!agentId && editable,
- });
-
- const savedForm = useMemo(
- () => (current ? formFromAttributes(fields, current) : emptyForm(fields)),
- [fields, current]
- );
-
- const [form, setForm] = useState<FormState>({});
- // Seed (and re-seed after save/agent change) from the persisted values. During
- // editing no refetch fires, so local edits are preserved until Save.
- useEffect(() => {
- setForm(savedForm);
- }, [savedForm]);
-
- const queryClient = useQueryClient();
- const mutation = useMutation({
- mutationFn: () =>
- rpc.agents.updateAgentDefinition({
- agentId: agentId as string,
- attributes: attributesFromForm(fields, form),
- }),
- onSuccess: () => {
- toast({ title: 'Advanced configuration saved' });
- void queryClient.invalidateQueries({ queryKey: ['agent-definition', agentId] });
- },
- onError: (error) => {
- log.error('Failed to save agent definition', { agentId, error });
- toast({
- title: 'Failed to save configuration',
- description: String(error),
- variant: 'destructive',
- });
- },
- });
-
- if (!editable || fields.length === 0) return null;
-
- const dirty =
- JSON.stringify(attributesFromForm(fields, form)) !==
- JSON.stringify(attributesFromForm(fields, savedForm));
-
- const setField = (key: string, value: FormValue) =>
- setForm((prev) => ({ ...prev, [key]: value }));
-
- return (
- <Field>
- <FieldTitle>Advanced configuration</FieldTitle>
- <FieldDescription className="text-foreground-muted">
- The agent&apos;s model, reasoning effort, tools, and system prompt. Saving rewrites its
- on-disk definition; the agent name is fixed.
- </FieldDescription>
- <div className="flex flex-col gap-4 rounded-md border border-border px-3 py-3">
- {fields.map((field) => (
- <Field key={field.key}>
- <FieldLabel htmlFor={`agent-definition-${field.key}`}>
- {field.label}
- {field.required || field.type === 'boolean' ? '' : ' (optional)'}
- </FieldLabel>
- <DefinitionFieldInput
- field={field}
- value={form[field.key] ?? (field.type === 'boolean' ? false : '')}
- onChange={(value) => setField(field.key, value)}
- />
- {field.help && (
- <FieldDescription className="text-foreground-muted">{field.help}</FieldDescription>
- )}
- </Field>
- ))}
- <div className="flex justify-end">
- <Button
- type="button"
- size="sm"
- disabled={!dirty || mutation.isPending}
- onClick={() => mutation.mutate()}
- >
- {mutation.isPending ? 'Saving...' : 'Save'}
- </Button>
- </div>
- </div>
- </Field>
- );
-}
diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
index 862f6ff68..d550dc9ca 100644
--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/settings-view/settings-panel.tsx
@@ -1,7 +1,7 @@
import { useQuery } from '@tanstack/react-query';
import { observer } from 'mobx-react-lite';
import { AddressingPolicySettingsSection } from '@renderer/features/locations/components/settings-view/sections/addressing-policy-settings-section';
-import { AgentDefinitionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/agent-definition-settings-section';
+import { AgentAdvancedSettingsSection } from '@renderer/features/locations/components/settings-view/sections/agent-advanced-settings-section';
import { AutoApproveSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-approve-settings-section';
import { AutoSessionSettingsSection } from '@renderer/features/locations/components/settings-view/sections/auto-session-settings-section';
import {
@@ -42,7 +42,7 @@ export const SettingsPanel = observer(function SettingsPanel() {
<AutoSessionSettingsSection locationId={locationId} agentId={agentId} />
<AutoApproveSettingsSection locationId={locationId} agentId={agentId} />
<AddressingPolicySettingsSection locationId={locationId} agentId={agentId} />
- <AgentDefinitionSettingsSection locationId={locationId} agentId={agentId} />
+ <AgentAdvancedSettingsSection locationId={locationId} agentId={agentId} />
</div>
);
});
diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.test.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.test.ts
index 97876ed17..9eacdf300 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.test.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.test.ts
@@ -1,5 +1,10 @@
import { describe, expect, it } from 'vitest';
-import { agentProviderConfig, toSwitchSpecialization } from './agent-provider-config';
+import {
+ agentProviderConfig,
+ attributesFromProviderConfig,
+ providerConfigFromAttributes,
+ toSwitchSpecialization,
+} from './agent-provider-config';
describe('agentProviderConfig schema', () => {
it('parses a versioned config and rejects an unversioned one', () => {
@@ -11,21 +16,31 @@ describe('agentProviderConfig schema', () => {
});
describe('toSwitchSpecialization', () => {
- it('maps effort → reasoningEffort and passes model/instructions through', () => {
+ it('passes every stored setting through under the key the profile writer reads', () => {
expect(
toSwitchSpecialization({
version: '1',
model: 'o3',
effort: 'high',
+ verbosity: 'low',
+ reasoningSummary: 'concise',
+ webSearch: 'true',
instructions: 'be terse',
})
- ).toEqual({ model: 'o3', reasoningEffort: 'high', instructions: 'be terse' });
+ ).toEqual({
+ model: 'o3',
+ effort: 'high',
+ verbosity: 'low',
+ reasoningSummary: 'concise',
+ webSearch: 'true',
+ instructions: 'be terse',
+ });
});
it('drops empty/whitespace fields so the base default stands', () => {
expect(
toSwitchSpecialization({ version: '1', model: ' ', effort: '', instructions: 'x' })
- ).toEqual({ model: undefined, reasoningEffort: undefined, instructions: 'x' });
+ ).toEqual({ instructions: 'x' });
});
it('returns undefined when nothing is set or the config is absent', () => {
@@ -35,3 +50,41 @@ describe('toSwitchSpecialization', () => {
expect(toSwitchSpecialization({ version: '1', model: ' ' })).toBeUndefined();
});
});
+
+describe('form attributes ↔ stored config', () => {
+ it('round-trips every setting', () => {
+ const config = {
+ version: '1' as const,
+ model: 'o3',
+ effort: 'none',
+ verbosity: 'high',
+ reasoningSummary: 'detailed',
+ webSearch: 'false',
+ instructions: 'be terse',
+ };
+
+ expect(providerConfigFromAttributes(attributesFromProviderConfig(config))).toEqual(config);
+ });
+
+ it('seeds a blank form from no config, and reads it back as nothing set', () => {
+ const attributes = attributesFromProviderConfig(null);
+
+ expect(attributes).toEqual({
+ model: '',
+ effort: '',
+ verbosity: '',
+ reasoningSummary: '',
+ webSearch: '',
+ instructions: '',
+ });
+ expect(providerConfigFromAttributes(attributes)).toBeNull();
+ });
+
+ it('keeps web search off as a stored value — unset and off are different', () => {
+ expect(providerConfigFromAttributes({ webSearch: 'false' })).toEqual({
+ version: '1',
+ webSearch: 'false',
+ });
+ expect(providerConfigFromAttributes({ webSearch: '' })).toBeNull();
+ });
+});
diff --git a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts
index 40757070b..e43115c8d 100644
--- a/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts
+++ b/console/apps/switch-console-desktop/src/shared/core/agents/agent-provider-config.ts
@@ -1,15 +1,26 @@
-import type { SwitchLaunchSpecialization } from '@switch-console/core/agents/plugins';
+import type {
+ RepoAgentAttributes,
+ SwitchLaunchSpecialization,
+} from '@switch-console/core/agents/plugins';
import z from 'zod';
import { defineVersionedSchema } from '@shared/lib/versioned-schema/versioned-schema';
/**
* Per-agent, provider-specific launch configuration. Today this carries the
* Codex specialization folded into the agent's Codex profile at launch — model,
- * reasoning effort, and a system-prompt/instructions body. Every field is
- * optional; an unset field leaves the provider/base-config default in place.
+ * reasoning effort, verbosity, reasoning summary, web search, and a
+ * system-prompt/instructions body.
+ *
+ * Every field is optional and an unset one is omitted from the profile, leaving
+ * the provider's own configuration to decide. That is deliberate for the on/off
+ * settings too: `webSearch` unset is not `webSearch` off — the first defers to
+ * the user's `~/.codex/config.toml`, the second overrides it. That is why it is
+ * a string rather than a boolean, since a boolean has no "unset".
*
* Stored as a versioned JSON column on the agent so the shape can evolve without
- * a migration per field, mirroring `sessions.config`.
+ * a migration per field, mirroring `sessions.config`. New fields are added as
+ * optional to the current version: a row written before they existed simply has
+ * none of them.
*/
const agentProviderConfigV1 = z.object({
version: z.literal('1'),
@@ -17,6 +28,12 @@ const agentProviderConfigV1 = z.object({
model: z.string().optional(),
/** Reasoning-effort id, e.g. a Codex `model_reasoning_effort` value. */
effort: z.string().optional(),
+ /** How much prose the model writes, e.g. Codex `model_verbosity`. */
+ verbosity: z.string().optional(),
+ /** How much reasoning is summarised back, e.g. Codex `model_reasoning_summary`. */
+ reasoningSummary: z.string().optional(),
+ /** `"true"` / `"false"` / unset — e.g. Codex `tools.web_search`. */
+ webSearch: z.string().optional(),
/** System-prompt/instructions body, carried in the agent's Codex profile as
* `developer_instructions` — additive to Codex's own instructions. */
instructions: z.string().optional(),
@@ -28,30 +45,65 @@ export const agentProviderConfig = defineVersionedSchema()
export type AgentProviderConfig = typeof agentProviderConfig.Type;
+/** The stored keys, which are also the field keys the provider declares. */
+const CONFIG_KEYS = [
+ 'model',
+ 'effort',
+ 'verbosity',
+ 'reasoningSummary',
+ 'webSearch',
+ 'instructions',
+] as const;
+
+const clean = (value: unknown): string | undefined => {
+ const trimmed = typeof value === 'string' ? value.trim() : '';
+ return trimmed ? trimmed : undefined;
+};
+
/**
* Map stored per-agent config to the launch-time specialization the profile
- * builder consumes. `effort` becomes `reasoningEffort`; empty/whitespace values
- * are dropped so the profile omits them and the base default stands. Returns
- * `undefined` when nothing is set, so callers pass no specialization at all.
+ * builder consumes. Empty/whitespace values are dropped so the profile omits
+ * them and the base default stands. Returns `undefined` when nothing is set, so
+ * callers pass no specialization at all.
*/
export function toSwitchSpecialization(
config: AgentProviderConfig | null | undefined
): SwitchLaunchSpecialization | undefined {
if (!config) return undefined;
- const clean = (value: string | undefined): string | undefined => {
- const trimmed = value?.trim();
- return trimmed ? trimmed : undefined;
- };
+ const specialization: SwitchLaunchSpecialization = {};
+ for (const key of CONFIG_KEYS) {
+ const value = clean(config[key]);
+ if (value !== undefined) specialization[key] = value;
+ }
+
+ return Object.keys(specialization).length > 0 ? specialization : undefined;
+}
- const specialization: SwitchLaunchSpecialization = {
- model: clean(config.model),
- reasoningEffort: clean(config.effort),
- instructions: clean(config.instructions),
- };
+/** Seed the advanced-configuration form from an agent's stored config. */
+export function attributesFromProviderConfig(
+ config: AgentProviderConfig | null | undefined
+): RepoAgentAttributes {
+ const attributes: RepoAgentAttributes = {};
+ for (const key of CONFIG_KEYS) attributes[key] = config?.[key] ?? '';
+ return attributes;
+}
- if (!specialization.model && !specialization.reasoningEffort && !specialization.instructions) {
- return undefined;
+/**
+ * Build the stored config from submitted form attributes. Null when every field
+ * is blank: an agent that specializes nothing gets no profile and no `--profile`
+ * argv, rather than an empty one.
+ */
+export function providerConfigFromAttributes(
+ attributes: RepoAgentAttributes
+): AgentProviderConfig | null {
+ const config: AgentProviderConfig = { version: '1' };
+ let set = false;
+ for (const key of CONFIG_KEYS) {
+ const value = clean(attributes[key]);
+ if (value === undefined) continue;
+ config[key] = value;
+ set = true;
}
- return specialization;
+ return set ? config : null;
}
diff --git a/console/packages/core/src/agents/plugins/capabilities/mcp.ts b/console/packages/core/src/agents/plugins/capabilities/mcp.ts
index e7262db3e..cb41ecd39 100644
--- a/console/packages/core/src/agents/plugins/capabilities/mcp.ts
+++ b/console/packages/core/src/agents/plugins/capabilities/mcp.ts
@@ -1,6 +1,7 @@
import z from 'zod';
import { definePluginCapability } from '../../../lib/plugins/capability';
import type { PluginFs } from '../../runtime/fs';
+import type { RepoAgentField } from './repo-agents';
export type McpTransport = 'stdio' | 'http';
@@ -24,12 +25,29 @@ export type SwitchLaunchProfile = {
args: string[];
};
-/** Optional per-agent specialization folded into the launch profile. */
+/**
+ * Optional per-agent specialization folded into the launch profile.
+ *
+ * Every value is a string, and an absent or empty one means "not set" — the
+ * provider's own configuration decides. That matters for the on/off settings:
+ * omitting `webSearch` leaves the user's base config alone, which is not the
+ * same as setting it to `false`.
+ *
+ * The keys are the field keys the provider declares in
+ * {@link IMcpBehavior.launchProfileFields}, so what the form collects and what
+ * the profile writer consumes are the same names end to end.
+ */
export type SwitchLaunchSpecialization = {
/** Model id, e.g. a Codex `model` override. */
model?: string;
- /** Reasoning-effort id, e.g. a Codex `model_reasoning_effort` override. */
- reasoningEffort?: string;
+ /** Reasoning-effort id, e.g. a Codex `model_reasoning_effort` value. */
+ effort?: string;
+ /** How much prose the model writes (Codex: `model_verbosity`). */
+ verbosity?: string;
+ /** How much reasoning is summarised back (Codex: `model_reasoning_summary`). */
+ reasoningSummary?: string;
+ /** `"true"` / `"false"` / unset — whether the agent may search the web. */
+ webSearch?: string;
/** A system-prompt/instructions body, carried in the profile itself (Codex:
* `developer_instructions`), which adds to the host's own operating
* instructions rather than replacing them. */
@@ -73,6 +91,20 @@ export type IMcpBehavior = {
* a name it is about to drop. Undefined for a provider that writes no profile.
*/
launchProfilePaths?(params: { slug: string; workingDir: string }): string[];
+ /**
+ * The per-agent fields that feed {@link launchProfile}, declared so the UI can
+ * collect them without knowing the provider.
+ *
+ * This is the launch-profile counterpart of `repoAgents.attributeFields()`:
+ * a provider keeps its per-agent settings either in a repo-agent definition or
+ * in a launch profile, and whichever it is, the same "advanced configuration"
+ * form renders these and the same editor saves them. Declaring them beside the
+ * profile builder that consumes them is what stops the field list and the TOML
+ * it produces drifting apart.
+ *
+ * Undefined for a provider that writes no profile.
+ */
+ launchProfileFields?(): RepoAgentField[];
};
export type McpServerRegistration = {
diff --git a/console/packages/plugins/src/agents/impl/codex/index.ts b/console/packages/plugins/src/agents/impl/codex/index.ts
index 7e066878b..df5fe5c77 100644
--- a/console/packages/plugins/src/agents/impl/codex/index.ts
+++ b/console/packages/plugins/src/agents/impl/codex/index.ts
@@ -9,7 +9,7 @@ import type { HostDependencyDescriptor, InstallOption } from '@switch-console/co
import { SWITCH_MARKETPLACE_SOURCE } from '../../../distribution';
import { buildCodexHookConfig, CODEX_HOOK_TRUST_FLAG } from './hooks';
import { icon } from './icon';
-import { codexLaunchProfile, codexProfilePaths } from './profile';
+import { codexLaunchProfile, codexLaunchProfileFields, codexProfilePaths } from './profile';
const CODEX_WINDOWS_INSTALL_SCRIPT =
'powershell -ExecutionPolicy ByPass -c "irm https://chatgpt.com/codex/install.ps1 | iex"';
@@ -154,5 +154,6 @@ export const provider = registerPluginBehavior(plugin, {
// Switch Console's.
launchProfile: codexLaunchProfile,
launchProfilePaths: codexProfilePaths,
+ launchProfileFields: codexLaunchProfileFields,
},
});
diff --git a/console/packages/plugins/src/agents/impl/codex/profile.test.ts b/console/packages/plugins/src/agents/impl/codex/profile.test.ts
index cb006199f..5e2965829 100644
--- a/console/packages/plugins/src/agents/impl/codex/profile.test.ts
+++ b/console/packages/plugins/src/agents/impl/codex/profile.test.ts
@@ -3,7 +3,10 @@ import { describe, expect, it } from 'vitest';
import {
buildCodexProfileToml,
CODEX_REASONING_EFFORTS,
+ CODEX_REASONING_SUMMARIES,
+ CODEX_VERBOSITY_LEVELS,
codexLaunchProfile,
+ codexLaunchProfileFields,
codexProfileName,
codexProfileRelativePath,
} from './profile';
@@ -17,7 +20,7 @@ describe('buildCodexProfileToml', () => {
// ("invalid transport"), taking the session with it.
const toml = buildCodexProfileToml({
model: 'gpt-5.6-terra',
- reasoningEffort: 'high',
+ effort: 'high',
instructions: 'be terse',
});
@@ -42,7 +45,7 @@ describe('buildCodexProfileToml', () => {
const parsed = parseTOML(
buildCodexProfileToml({
model: 'gpt-5.6-terra',
- reasoningEffort: 'high',
+ effort: 'high',
instructions: 'be terse',
})
) as Record<string, unknown>;
@@ -149,7 +152,7 @@ describe('codexLaunchProfile', () => {
});
it('exposes the stable reasoning-effort levels', () => {
- expect(CODEX_REASONING_EFFORTS).toEqual(['low', 'medium', 'high', 'xhigh', 'max']);
+ expect(CODEX_REASONING_EFFORTS).toEqual(['none', 'low', 'medium', 'high', 'xhigh', 'max']);
});
});
@@ -188,3 +191,66 @@ describe('codexProfileName', () => {
expect(profile.files[0].content).toContain('developer_instructions = "be terse"');
});
});
+
+describe('codexLaunchProfileFields', () => {
+ it('declares exactly the keys the profile builder consumes', () => {
+ expect(codexLaunchProfileFields().map((field) => field.key)).toEqual([
+ 'model',
+ 'effort',
+ 'verbosity',
+ 'reasoningSummary',
+ 'webSearch',
+ 'instructions',
+ ]);
+ });
+
+ it('offers every reasoning effort the profile accepts, plus an unset default', () => {
+ const effort = codexLaunchProfileFields().find((field) => field.key === 'effort');
+
+ expect(effort?.options?.map((option) => option.value)).toEqual([
+ '',
+ ...CODEX_REASONING_EFFORTS,
+ ]);
+ });
+
+ it('writes every declared field, so a field cannot be collected and then dropped', () => {
+ const filled = Object.fromEntries(
+ codexLaunchProfileFields().map((field) => [
+ field.key,
+ field.key === 'webSearch' ? 'true' : 'x',
+ ])
+ );
+
+ const toml = parseTOML(buildCodexProfileToml(filled));
+
+ expect(Object.keys(toml).sort()).toEqual([
+ 'developer_instructions',
+ 'model',
+ 'model_reasoning_effort',
+ 'model_reasoning_summary',
+ 'model_verbosity',
+ 'tools',
+ ]);
+ expect((toml.tools as Record<string, unknown>).web_search).toBe(true);
+ });
+
+ it('offers only the verbosity and summary values Codex accepts', () => {
+ const optionsFor = (key: string) =>
+ codexLaunchProfileFields()
+ .find((field) => field.key === key)
+ ?.options?.map((option) => option.value);
+
+ expect(optionsFor('verbosity')).toEqual(['', ...CODEX_VERBOSITY_LEVELS]);
+ expect(optionsFor('reasoningSummary')).toEqual(['', ...CODEX_REASONING_SUMMARIES]);
+ });
+
+ it('turns web search off explicitly, which is not the same as leaving it unset', () => {
+ const off = parseTOML(buildCodexProfileToml({ webSearch: 'false' }));
+ expect((off.tools as Record<string, unknown>).web_search).toBe(false);
+
+ // Unset writes nothing at all, so the user's own config still decides.
+ // An empty profile still stringifies to a newline, which is why the
+ // no-profile check in `codexLaunchProfile` tests the trimmed result.
+ expect(buildCodexProfileToml({ webSearch: '' }).trim()).toBe('');
+ });
+});
diff --git a/console/packages/plugins/src/agents/impl/codex/profile.ts b/console/packages/plugins/src/agents/impl/codex/profile.ts
index 34cd2d297..08ce634ad 100644
Binary files a/console/packages/plugins/src/agents/impl/codex/profile.ts and b/console/packages/plugins/src/agents/impl/codex/profile.ts differ