Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 3 additions & 7 deletions src/main/claude/claude-structured-session-adapter.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -592,13 +592,9 @@ describe('ClaudeStructuredSessionAdapter turns and controls', () => {
const adapter = await acquired(claude)
const result = await adapter.readOptions({ sessionId: 'session-1', fence: 7 })

expect(result.models.map((model) => model.id)).toEqual([
'fable',
'opus',
'sonnet',
'haiku',
'custom-model'
])
// Was: a trailing `custom-model` row. The seed is a list of available ids, and the
// init frame's unlisted model is reported as current without being offered.
expect(result.models.map((model) => model.id)).toEqual(['fable', 'opus', 'sonnet', 'haiku'])
expect(result.current).toEqual({
model: 'custom-model',
effort: 'high',
Expand Down
65 changes: 65 additions & 0 deletions src/main/claude/claude-structured-session-options.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import { describe, expect, it } from 'vitest'
import { readClaudeStructuredSessionOptions } from './claude-structured-session-options'
import type { ClaudeSession } from './claude-structured-session-state'

// `list_models` rows as the CLI reports them: the `default` row carries only the
// resolved id, which is what marks the listed alias that resolves to the same model.
const LISTED_ROWS = [
{ value: 'default', resolvedModel: 'claude-opus-5[1m]' },
{
value: 'opus[1m]',
displayName: 'Opus (1M context)',
resolvedModel: 'claude-opus-5[1m]',
supportsEffort: true,
supportedEffortLevels: ['low', 'high']
},
{ value: 'sonnet', displayName: 'Sonnet', resolvedModel: 'claude-sonnet-5' }
]

function optionsSession(reportedModel: string): ClaudeSession {
return {
connection: { supportedModels: async () => LISTED_ROWS },
options: new Map(),
reportedOptions: { model: reportedModel },
optionMutationSequence: 0,
reportedModelMutation: 0,
confirmedOptions: new Set()
} as unknown as ClaudeSession
}

describe('readClaudeStructuredSessionOptions', () => {
it('names the listed alias the init frame’s resolved id belongs to', async () => {
// The pill shows a picked Opus as `opus[1m]`, not as the resolved id the session
// reports — the mapping, not a fabricated row, is what keeps that model nameable.
const options = await readClaudeStructuredSessionOptions(
optionsSession('claude-opus-5[1m]'),
undefined
)

expect(options.current).toEqual({ model: 'opus[1m]', confirmed: ['model'] })
expect(options.models).toEqual([
{
id: 'opus[1m]',
label: 'Opus (1M context)',
isDefault: true,
efforts: [
{ value: 'low', label: 'Low' },
{ value: 'high', label: 'High' }
]
},
{ id: 'sonnet', label: 'Sonnet', isDefault: false, efforts: [] }
])
})

it('reports an unlisted current model without listing it', async () => {
// Was: a fabricated `{ id: model, label: model, efforts: [] }` row, which offered a
// raw launch flag (`worker-start --model claude-opus-5`) as if the CLI listed it.
const options = await readClaudeStructuredSessionOptions(
optionsSession('claude-opus-5'),
undefined
)

expect(options.current.model).toBe('claude-opus-5')
expect(options.models.map((model) => model.id)).toEqual(['opus[1m]', 'sonnet'])
})
})
6 changes: 3 additions & 3 deletions src/main/claude/claude-structured-session-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,10 @@ export async function readClaudeStructuredSessionOptions(
const discovered = listedModels(catalog ? { models: catalog } : null)
const models = discovered.length > 0 ? discovered : seedModels()
const current = readClaudeCurrentModel(session)
// `models` stays the CLI's own list (or the seed): `currentModelId` already maps a
// resolved id back onto a listed row, so what survives unmatched is an id the CLI
// never offered. It is reported as current — the session runs it — but not listed.
const model = currentModelId(models, current.id)
if (!models.some((entry) => entry.id === model)) {
models.push({ id: model, label: model, isDefault: false, efforts: [], resolvedModel: null })
}
const effort = session.options.get('effort') ?? session.reportedOptions.effort
const confirmed = [
...(current.confirmed ? ['model'] : []),
Expand Down
134 changes: 134 additions & 0 deletions src/main/codex/codex-structured-session-options.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
import { describe, expect, it, vi } from 'vitest'
import { CODEX_SESSION_OPTION_CATALOG } from '../../shared/agent-session-option-catalog-claude-codex'
import {
applyStructuredAgentSessionOptions,
canSetStructuredAgentSessionOption,
createStructuredAgentSessionOptionState,
structuredAgentSessionOptionSnapshot
} from '../../shared/structured-agent-session-options'
import type { CodexAppServerConnection } from './codex-app-server-connection'
import { CodexAcquisitionWindow } from './codex-structured-acquisition-window'
import {
applyCodexStructuredSessionOption,
readCodexStructuredSessionOptions,
readLiveCodexSessionOptions,
reportedCodexThreadOptions,
restoredCodexSessionOptions
} from './codex-structured-session-options'
Expand Down Expand Up @@ -123,6 +131,107 @@ describe('structured Codex session options', () => {
)
})

it('reports an unlisted current model without offering it as a choice', async () => {
// Was: a fabricated `{ id, label: id, efforts: [] }` row, which offered a raw launch
// id in the picker as though the account were entitled to it.
const request = vi.fn(async () => ({
data: [{ model: 'gpt-live', displayName: 'GPT Live', isDefault: true }],
nextCursor: null
}))

await expect(
readCodexStructuredSessionOptions({
connection: { request } as never,
current: { model: 'gpt-unlisted' }
})
).resolves.toEqual({
models: [{ id: 'gpt-live', label: 'GPT Live', isDefault: true, efforts: [] }],
current: { model: 'gpt-unlisted' }
})
})

it('confirms a model the thread reported, but not a pick we restored', async () => {
// The display rule names an unlisted model only when the agent reported it, so the
// reader has to say which of the two answered. `session.options` is a restored pick
// or an unechoed write of ours; `reportedOptions` is the opened thread's own state.
const request = vi.fn(async () => ({
data: [{ model: 'gpt-live', displayName: 'GPT Live', isDefault: true }],
nextCursor: null
}))
const session = (
options: Map<string, string>,
reported: Record<string, string>
): CodexSession =>
({ connection: { request }, options, reportedOptions: reported }) as unknown as CodexSession

await expect(
readLiveCodexSessionOptions(session(new Map(), { model: 'gpt-unlisted' }), undefined)
).resolves.toMatchObject({ current: { model: 'gpt-unlisted', confirmed: ['model'] } })

const restored = await readLiveCodexSessionOptions(
session(new Map([['model', 'gpt-stale']]), {}),
undefined
)
expect(restored.current).toEqual({ model: 'gpt-stale' })
expect(restored.current.confirmed).toBeUndefined()

const changedModel = await readLiveCodexSessionOptions(
session(new Map([['model', 'gpt-stale']]), { model: 'gpt-old', effort: 'high' }),
undefined
)
expect(changedModel.current).toEqual({ model: 'gpt-stale', effort: 'high' })
expect(changedModel.current.confirmed).toBeUndefined()
})

it('confirms a restored model when the opened thread reported the same value', async () => {
const request = vi.fn(async () => ({
data: [{ model: 'gpt-live', displayName: 'GPT Live', isDefault: true }],
nextCursor: null
}))
const restored = {
connection: { request },
options: new Map([['model', 'gpt-unlisted']]),
reportedOptions: { model: 'gpt-unlisted' }
} as unknown as CodexSession

const result = await readLiveCodexSessionOptions(restored, undefined)
expect(result).toMatchObject({
current: { model: 'gpt-unlisted', confirmed: ['model'] }
})
const state = applyStructuredAgentSessionOptions(
createStructuredAgentSessionOptionState('codex'),
CODEX_SESSION_OPTION_CATALOG,
result
)
const model = structuredAgentSessionOptionSnapshot(state)[0]!
expect(model).toMatchObject({
valueSource: 'reported',
kind: { currentValue: 'gpt-unlisted' }
})
expect(model.kind.type === 'select' ? model.kind.choices : []).not.toContainEqual(
expect.objectContaining({ value: 'gpt-unlisted' })
)
})

it('does not confirm a model it substituted rather than read', async () => {
// With nothing current the reader picks the default; that is our choice, not a report.
const request = vi.fn(async () => ({
data: [{ model: 'gpt-live', displayName: 'GPT Live', isDefault: true }],
nextCursor: null
}))

await expect(
readCodexStructuredSessionOptions({
connection: { request } as never,
current: {},
confirmed: ['model']
})
).resolves.toEqual({
models: [{ id: 'gpt-live', label: 'GPT Live', isDefault: true, efforts: [] }],
current: { model: 'gpt-live' }
})
})

it('hydrates current values from thread start or resume', () => {
expect(
reportedCodexThreadOptions({
Expand Down Expand Up @@ -158,6 +267,31 @@ describe('structured Codex session options', () => {
).resolves.toEqual({ model: 'gpt-fast', effort: 'low' })
})

it('applies a catalog-safe effort to a running unlisted model', async () => {
const session = optionSession(
vi.fn(async () => ({
data: [{ model: 'gpt-live', supportedReasoningEfforts: [{ reasoningEffort: 'high' }] }],
nextCursor: null
}))
)
session.reportedOptions = { model: 'gpt-unlisted', effort: 'medium' }
const result = await readLiveCodexSessionOptions(session, undefined)
const state = applyStructuredAgentSessionOptions(
createStructuredAgentSessionOptionState('codex'),
CODEX_SESSION_OPTION_CATALOG,
result
)
expect(canSetStructuredAgentSessionOption(state, 'effort', 'high')).toBe(true)

await expect(
applyCodexStructuredSessionOption(session, 'effort', 'high', undefined)
).resolves.toEqual({ model: 'gpt-unlisted', effort: 'high' })
expect(session.reportedOptions).toEqual({ model: 'gpt-unlisted' })
await expect(readLiveCodexSessionOptions(session, undefined)).resolves.toMatchObject({
current: { model: 'gpt-unlisted', effort: 'high', confirmed: ['model'] }
})
})

it('rejects values absent from the provider catalog', async () => {
const session = optionSession(
vi.fn(async () => ({
Expand Down
65 changes: 50 additions & 15 deletions src/main/codex/codex-structured-session-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type {
AgentSessionOptionChoice,
AgentSessionOptionsResult
} from '../../shared/agent-session-wire'
import { resolveCatalogModelOptions } from '../../shared/agent-session-option-catalog'
import { CODEX_SESSION_OPTION_CATALOG } from '../../shared/agent-session-option-catalog-claude-codex'
import type { CodexAppServerConnection } from './codex-app-server-connection'
import type { CodexOpenedThread } from './codex-structured-thread-open'
import type { CodexSession } from './codex-structured-session-state'
Expand All @@ -12,6 +14,19 @@ import { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wi
const MODEL_PAGE_LIMIT = 100
const MAX_MODEL_PAGES = 20

function supportedEfforts(
model: AgentSessionModelOption | undefined,
modelId: string
): readonly AgentSessionOptionChoice[] {
if (model) {
return model.efforts
}
const fallback = resolveCatalogModelOptions(CODEX_SESSION_OPTION_CATALOG, [], modelId).find(
(option) => option.id === 'effort'
)
return fallback?.kind.type === 'select' ? fallback.kind.choices : []
}

export function restoredCodexSessionOptions(
options: Readonly<Record<string, string>> | undefined
): Map<string, string> {
Expand Down Expand Up @@ -78,6 +93,9 @@ function modelOption(value: unknown): AgentSessionModelOption | null {
export async function readCodexStructuredSessionOptions(input: {
connection: Pick<CodexAppServerConnection, 'request'>
current: { model?: string; effort?: string }
/** Ids in `current` that came from the thread's own state rather than from a value we
* wrote. Only the caller knows which answered, so it must say. */
confirmed?: readonly string[]
timeoutMs?: number
}): Promise<AgentSessionOptionsResult> {
const models: AgentSessionModelOption[] = []
Expand All @@ -102,21 +120,21 @@ export async function readCodexStructuredSessionOptions(input: {
break
}
}
if (input.current.model && !models.some((model) => model.id === input.current.model)) {
models.push({
id: input.current.model,
label: input.current.model,
isDefault: false,
efforts: []
})
}
// `models` stays what `model/list` offered: a current id the account cannot select is
// still reported (the thread runs it) but never listed, so no raw id is offerable.
const model = input.current.model ?? models.find((entry) => entry.isDefault)?.id ?? models[0]?.id
if (!model) {
throw new Error('codex app-server returned no available models')
}
// Never pass on a confirmation for a model this function substituted rather than read.
const confirmed = input.confirmed?.filter((id) => id !== 'model' || model === input.current.model)
return {
models,
current: { model, ...(input.current.effort ? { effort: input.current.effort } : {}) }
current: {
model,
...(input.current.effort ? { effort: input.current.effort } : {}),
...(confirmed?.length ? { confirmed } : {})
}
}
}

Expand All @@ -133,11 +151,21 @@ export function readLiveCodexSessionOptions(
session: CodexSession,
timeoutMs: number | undefined
): Promise<AgentSessionOptionsResult> {
const model = session.options.get('model') ?? session.reportedOptions.model
const effort = session.options.get('effort') ?? session.reportedOptions.effort
const pendingModel = session.options.get('model')
const pendingEffort = session.options.get('effort')
const model = pendingModel ?? session.reportedOptions.model
const effort = pendingEffort ?? session.reportedOptions.effort
// A matching restored override still has the opened thread's evidence. Successful
// writes clear that evidence below, so equality cannot reuse a stale report.
const modelConfirmed = Boolean(model && model === session.reportedOptions.model)
const confirmed = [
...(modelConfirmed ? ['model'] : []),
...(modelConfirmed && effort && effort === session.reportedOptions.effort ? ['effort'] : [])
]
return readCodexStructuredSessionOptions({
connection: session.connection,
current: { ...(model ? { model } : {}), ...(effort ? { effort } : {}) },
...(confirmed.length > 0 ? { confirmed } : {}),
timeoutMs
})
}
Expand Down Expand Up @@ -180,19 +208,26 @@ async function applyValidatedCodexStructuredSessionOption(
}
const modelId = key === 'model' ? value : catalog.current.model
const model = catalog.models.find((entry) => entry.id === modelId)
const efforts = supportedEfforts(model, modelId)
const requestedEffort = key === 'effort' ? value : priorEffort
if (
key === 'effort' &&
(!model?.efforts.length || !model.efforts.some((effort) => effort.value === requestedEffort))
(!efforts.length || !efforts.some((effort) => effort.value === requestedEffort))
) {
throw new Error(`codex app-server model ${modelId} does not support ${value}`)
}
const effort =
model?.efforts.length === 0
efforts.length === 0
? undefined
: (model?.efforts.find((entry) => entry.value === requestedEffort)?.value ??
: (efforts.find((entry) => entry.value === requestedEffort)?.value ??
model?.defaultEffort ??
model?.efforts[0]?.value)
efforts[0]?.value)
if (key === 'model') {
delete session.reportedOptions.model
delete session.reportedOptions.effort
} else {
delete session.reportedOptions.effort
}
session.options.set('model', modelId)
if (effort) {
session.options.set('effort', effort)
Expand Down
Loading