Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
2 changes: 1 addition & 1 deletion src/main/claude/claude-stream-json-connection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ describe('Claude stream-json connection', () => {
const session = {
connection,
options: new Map<string, string>(),
reusableOptions: new Map<string, string>(),
appliedInputOptions: new Map<string, string>(),
reportedOptions: {},
startup: { state: 'proven' }
} as unknown as ClaudeSession
Expand Down
2 changes: 1 addition & 1 deletion src/main/claude/claude-structured-dispatch-test-support.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export function sessionFor(send: Mock = vi.fn().mockResolvedValue(undefined)): C
reportedOptions: {},
reportedModelMutation: 0,
confirmedOptions: new Set(),
reusableOptions: new Map(),
appliedInputOptions: new Map(),
launchedModel: null,
fastModeAtStart: false,
capabilities: [],
Expand Down
8 changes: 4 additions & 4 deletions src/main/claude/claude-structured-effort-reporting.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ function sessionWith(
optionMutationSequence: 0,
reportedModelMutation: 0,
confirmedOptions: new Set<string>(),
reusableOptions: new Map(),
appliedInputOptions: new Map(),
connection: {
supportedModels: async () => {
calls.push('list_models')
Expand Down Expand Up @@ -195,15 +195,15 @@ describe('Claude effort against the model that must run it', () => {
})

it('sends `max`, which the readback cannot report, when the model advertises it', async () => {
// UNREPORTED_EFFORTS still governs: no get_settings, so no false disagreement.
// The underlying setting may differ from a transient execution effort.
const { session, calls } = sessionWith('high', [], { model: 'sonnet', catalog: [SONNET] })

await expect(
setClaudeStructuredOption(session, { key: 'effort', value: 'max' }, undefined)
).resolves.toEqual({ model: 'sonnet', effort: 'max' })
expect(calls).toEqual(['list_models', 'apply:max'])
expect(calls).toEqual(['list_models', 'apply:max', 'get_settings'])
await readClaudeStructuredSessionOptions(session, undefined)
expect(session.reusableOptions.get('effort')).toBe('max')
expect(session.appliedInputOptions.get('effort')).toBe('max')
expect(session.confirmedOptions.has('effort')).toBe(false)
})

Expand Down
82 changes: 82 additions & 0 deletions src/main/claude/claude-structured-message-options.test.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { describe, expect, it, vi } from 'vitest'
import {
acquired,
adapterFor,
claudeFrame,
fakeClaude,
identityFor,
recordingJournalSink,
USER_MESSAGE
} from './claude-structured-session-test-support'
import { captureStructuredExecutionOptions } from '../native-chat/agent-session-wire/structured-agent-session-execution-options'
Expand All @@ -26,6 +29,85 @@
]

describe('Claude accepted message choices', () => {
it.each([false, true])(
'delivers resumed choices despite optional reports (alias listed: %s)',
async (listed) => {
const saved = { model: 'opus[1m]', effort: 'high', fastMode: 'false' }
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const models = listed ? [...MODELS, { value: saved.model }] : MODELS
const claude = fakeClaude({ initModels: models, routes: { list_models: () => models } })
const adapter = adapterFor(claude, { resumesTranscript: true })
await adapter.acquire({
identity: identityFor(),
fence: 7,
spawnToken: 'resume',
options: saved,
events: recordingJournalSink()
})
const connection = claude.connections[0]!
claudeFrame(connection, { type: 'system', subtype: 'init', model: 'claude-opus-5' })
connection.calls.length = 0
for (const clientMessageId of ['restart', 'followup']) {
await expect(
adapter.dispatch({
sessionId: 'session-1',
clientMessageId,
body: USER_MESSAGE,
executionOptions: saved,

Check failure on line 55 in src/main/claude/claude-structured-message-options.test.ts

View workflow job for this annotation

GitHub Actions / static analysis and typecheck

TS2322

Type '{ model: string; effort: string; fastMode: string; }' is not assignable to type '{ model?: string | undefined; effort?: string | undefined; personality?: string | undefined; fastMode?: "false" | "true" | undefined; serviceTier?: string | undefined; }'. Types of property 'fastMode' are incompatible. Type 'string' is not assignable to type '"false" | "true" | undefined'.

Check failure on line 55 in src/main/claude/claude-structured-message-options.test.ts

View workflow job for this annotation

GitHub Actions / static analysis and typecheck

Type '{ model: string; effort: string; fastMode: string; }' is not assignable to type '{ model?: string | undefined; effort?: string | undefined; personality?: string | undefined; fastMode?: "false" | "true" | undefined; serviceTier?: string | undefined; }'.
fence: 7
})
).resolves.toEqual({ state: 'admitted' })
await adapter.readOptions({ sessionId: 'session-1', fence: 7 })
}
expect(
connection.calls.filter((call) =>
['set_model', 'apply_flag_settings'].includes(call.subtype)
)
).toEqual([])
for (const clientMessageId of ['changed', 'unchanged']) {
await expect(
adapter.dispatch({
sessionId: 'session-1',
clientMessageId,
body: USER_MESSAGE,
executionOptions: { ...saved, model: 'custom[1m]', effort: 'low' },

Check failure on line 72 in src/main/claude/claude-structured-message-options.test.ts

View workflow job for this annotation

GitHub Actions / static analysis and typecheck

TS2322

Type '{ fastMode: string; model: string; effort: string; }' is not assignable to type '{ model?: string | undefined; effort?: string | undefined; personality?: string | undefined; fastMode?: "false" | "true" | undefined; serviceTier?: string | undefined; }'. Types of property 'fastMode' are incompatible. Type 'string' is not assignable to type '"false" | "true" | undefined'.

Check failure on line 72 in src/main/claude/claude-structured-message-options.test.ts

View workflow job for this annotation

GitHub Actions / static analysis and typecheck

Type '{ fastMode: string; model: string; effort: string; }' is not assignable to type '{ model?: string | undefined; effort?: string | undefined; personality?: string | undefined; fastMode?: "false" | "true" | undefined; serviceTier?: string | undefined; }'.
fence: 7
})
).resolves.toEqual({ state: 'admitted' })
}
expect(
connection.calls.filter((call) =>
['set_model', 'apply_flag_settings'].includes(call.subtype)
)
).toEqual([
{ subtype: 'set_model', params: { model: 'custom[1m]' } },
{ subtype: 'apply_flag_settings', params: { settings: { effortLevel: 'low' } } }
])
const failure = new Error('control refused')
connection.setModel = async () => {
throw failure
}
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})
try {
await expect(
adapter.dispatch({
sessionId: 'session-1',
clientMessageId: `refused-${listed}`,
body: USER_MESSAGE,
executionOptions: { model: 'another' },
fence: 7
})
).resolves.toMatchObject({ state: 'rejected' })
expect(connection.sent).toHaveLength(4)
expect(warn).toHaveBeenCalledWith(
expect.any(String),
expect.objectContaining({ error: failure })
)
} finally {
warn.mockRestore()
}
}
)

it('applies a held message A before its prompt, then message B on the existing child', async () => {
const order: string[] = []
let currentEffort = 'high'
Expand Down
31 changes: 22 additions & 9 deletions src/main/claude/claude-structured-message-options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@ import { dispatchClaudeTurn } from './claude-structured-dispatch'
import type { StructuredAgentSessionAdapter } from '../native-chat/agent-session-wire/structured-agent-session-adapter'
import type { AgentSessionExecutionOptions } from '../../shared/agent-session-execution-options'
import { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wire/structured-agent-session-option-error'
import {
createStructuredAgentSessionLogger,
neverThrowingStructuredAgentSessionLogger,
type StructuredAgentSessionLogger
} from '../native-chat/agent-session-wire/structured-agent-session-logger'
import { listedModels } from './claude-structured-model-catalog'
import { setClaudeStructuredOption } from './claude-structured-options'
import type { ClaudeSession } from './claude-structured-session-state'
import { throwIfSignalAborted, waitForPromiseWithSignal } from '../../shared/abort-signal-reason'

const defaultLogger = createStructuredAgentSessionLogger()

/** Applies the accepted message's choices while its prompt is still in the SDK input queue. */
export async function applyClaudeMessageOptions(
session: ClaudeSession,
Expand All @@ -16,7 +23,7 @@ export async function applyClaudeMessageOptions(
): Promise<void> {
throwIfSignalAborted(signal)
const model = options.model ?? (await defaultModelForMessage(session, timeoutMs, signal))
if (model && session.reusableOptions.get('model') !== model) {
if (model && session.appliedInputOptions.get('model') !== model) {
await waitForPromiseWithSignal(
setClaudeStructuredOption(session, { key: 'model', value: model }, timeoutMs),
signal
Expand All @@ -25,28 +32,24 @@ export async function applyClaudeMessageOptions(

throwIfSignalAborted(signal)
const effort = options.effort ?? session.configuredDefaults?.effort
if (effort && session.reusableOptions.get('effort') !== effort) {
if (effort && session.appliedInputOptions.get('effort') !== effort) {
await waitForPromiseWithSignal(
setClaudeStructuredOption(session, { key: 'effort', value: effort }, timeoutMs),
signal
)
} else if (!effort && session.options.has('effort')) {
// Omission restores configuration; without its value a live control cannot clear the override.
throw new AgentSessionOptionRejectedError('Claude did not report its configured effort')
}

throwIfSignalAborted(signal)
const fastMode = options.fastMode
if (fastMode !== undefined && session.reusableOptions.get('fastMode') !== fastMode) {
if (fastMode !== undefined && session.appliedInputOptions.get('fastMode') !== fastMode) {
await waitForPromiseWithSignal(
setClaudeStructuredOption(session, { key: 'fastMode', value: fastMode }, timeoutMs),
signal
)
}
for (const [key, value] of Object.entries({ model, effort, fastMode })) {
if (value !== undefined && session.reusableOptions.get(key) !== value) {
throw new AgentSessionOptionRejectedError(`Claude did not apply ${key} ${value}`)
}
}
throwIfSignalAborted(signal)
}

Expand Down Expand Up @@ -77,7 +80,8 @@ async function defaultModelForMessage(
export function dispatchClaudeMessage(
session: ClaudeSession,
input: Parameters<StructuredAgentSessionAdapter['dispatch']>[0],
timeoutMs: number | undefined
timeoutMs: number | undefined,
logger: StructuredAgentSessionLogger = defaultLogger
): ReturnType<StructuredAgentSessionAdapter['dispatch']> {
const messageOptions = input.executionOptions
return dispatchClaudeTurn(
Expand All @@ -91,6 +95,15 @@ export function dispatchClaudeMessage(
await applyClaudeMessageOptions(session, messageOptions, timeoutMs, input.signal)
input.signal?.throwIfAborted()
} catch (error) {
neverThrowingStructuredAgentSessionLogger(logger).warn(
'applying Claude message choices failed',
{
scope: 'claude-message-options',
sessionId: input.sessionId,
clientMessageId: input.clientMessageId,
error
}
)
throw error instanceof AgentSessionOptionRejectedError
? error
: new AgentSessionOptionRejectedError(error)
Expand Down
4 changes: 2 additions & 2 deletions src/main/claude/claude-structured-model-confirmation.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,7 @@ describe('Claude effort the settings readback cannot report', () => {
reportedOptions: {},
optionMutationSequence: 0,
confirmedOptions: new Set<string>(),
reusableOptions: new Map(),
appliedInputOptions: new Map(),
connection: {
supportedModels: async () => {
calls.push('list_models')
Expand Down Expand Up @@ -219,6 +219,6 @@ describe('Claude effort the settings readback cannot report', () => {
await expect(
setClaudeStructuredOption(session, { key: 'effort', value: 'max' }, undefined)
).resolves.toEqual({ model: 'sonnet', effort: 'max' })
expect(calls).toEqual(['list_models', 'apply:max'])
expect(calls).toEqual(['list_models', 'apply:max', 'get_settings'])
})
})
76 changes: 13 additions & 63 deletions src/main/claude/claude-structured-model-preflight.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { describe, expect, it } from 'vitest'
import { AgentSessionOptionRejectedError } from '../native-chat/agent-session-wire/structured-agent-session-option-error'
import { setClaudeStructuredOption } from './claude-structured-options'
import type { ClaudeSession } from './claude-structured-session-state'

Expand All @@ -22,7 +21,7 @@ function sessionWith(catalog: readonly Record<string, unknown>[] | 'unavailable'
optionMutationSequence: 0,
reportedModelMutation: 0,
confirmedOptions: new Set<string>(),
reusableOptions: new Map(),
appliedInputOptions: new Map(),
connection: {
supportedModels: async () => {
calls.push('list_models')
Expand All @@ -41,65 +40,16 @@ function sessionWith(catalog: readonly Record<string, unknown>[] | 'unavailable'
}
}

describe('Claude model pre-flight against the catalog the CLI listed', () => {
it('refuses a model the provider does not list', async () => {
const { session, calls } = sessionWith([DEFAULT_ROW, SONNET, HAIKU])

await expect(
setClaudeStructuredOption(session, { key: 'model', value: 'not-a-real-model-xyz' }, undefined)
).rejects.toBeInstanceOf(AgentSessionOptionRejectedError)
// Measured on Claude Code 2.1.260: set_model resolves for an unlisted id and
// every later turn returns is_error with zero tokens. Nothing undoes the
// write, so the refusal has to land before it.
expect(calls).toEqual(['list_models'])
expect(session.options.has('model')).toBe(false)
})

it('applies a model the provider lists', async () => {
const { session, calls } = sessionWith([DEFAULT_ROW, SONNET, HAIKU])

await expect(
setClaudeStructuredOption(session, { key: 'model', value: 'haiku' }, undefined)
).resolves.toEqual({ model: 'haiku' })
expect(calls).toEqual(['list_models', 'set_model:haiku'])
})

it('applies a resolved model id the catalog carries only under its alias', async () => {
const { session, calls } = sessionWith([DEFAULT_ROW, SONNET])

await expect(
setClaudeStructuredOption(session, { key: 'model', value: 'claude-sonnet-5' }, undefined)
).resolves.toEqual({ model: 'claude-sonnet-5' })
expect(calls).toEqual(['list_models', 'set_model:claude-sonnet-5'])
})

it('refuses nothing when list_models is unavailable', async () => {
// A CLI predating list_models would otherwise have every model refused.
const { session, calls } = sessionWith('unavailable')

await expect(
setClaudeStructuredOption(session, { key: 'model', value: 'sonnet' }, undefined)
).resolves.toEqual({ model: 'sonnet' })
expect(calls).toEqual(['list_models', 'set_model:sonnet'])
})

it('refuses nothing when the listed catalog is empty', async () => {
// An empty answer identifies no model, so it is not evidence against one.
const { session, calls } = sessionWith([])

await expect(
setClaudeStructuredOption(session, { key: 'model', value: 'sonnet' }, undefined)
).resolves.toEqual({ model: 'sonnet' })
expect(calls).toEqual(['list_models', 'set_model:sonnet'])
})

it('refuses nothing when the catalog carries only the synthetic default row', async () => {
// listedModels drops that row, leaving a list that identifies no model.
const { session, calls } = sessionWith([DEFAULT_ROW])

await expect(
setClaudeStructuredOption(session, { key: 'model', value: 'sonnet' }, undefined)
).resolves.toEqual({ model: 'sonnet' })
expect(calls).toEqual(['list_models', 'set_model:sonnet'])
})
describe('Claude literal model controls', () => {
it.each(['opus[1m]', 'claude-sonnet-5'])(
'passes %s through an incomplete catalog',
async (model) => {
const { session, calls } = sessionWith([DEFAULT_ROW, SONNET, HAIKU])
await expect(
setClaudeStructuredOption(session, { key: 'model', value: model }, undefined)
).resolves.toEqual({ model })
expect(calls).toEqual([`set_model:${model}`])
expect(session.appliedInputOptions.get('model')).toBe(model)
}
)
})
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ describe('confirmation never outlives the write it belongs to', () => {
reportedOptions: {},
optionMutationSequence: 0,
confirmedOptions: new Set<string>(),
reusableOptions: new Map(),
appliedInputOptions: new Map(),
connection: {
supportedModels: async () => CATALOG,
applyFlagSettings: async (s: { effortLevel?: string }) => {
Expand Down
7 changes: 4 additions & 3 deletions src/main/claude/claude-structured-options.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function sessionFor(setModel: ClaudeSession['connection']['setModel']): ClaudeSe
reportedOptions: {},
reportedModelMutation: 0,
confirmedOptions: new Set(),
reusableOptions: new Map(),
appliedInputOptions: new Map(),
launchedModel: null,
fastModeAtStart: false,
capabilities: [],
Expand Down Expand Up @@ -296,6 +296,7 @@ describe('Claude structured Fast mode', () => {
setClaudeStructuredOption(session, { key: 'model', value: 'haiku' }, undefined)
).resolves.toMatchObject({ model: 'haiku', fastMode: 'false' })
expect(applyFlagSettings).toHaveBeenCalledWith({ fastMode: false }, { timeoutMs: undefined })
expect(session.appliedInputOptions.get('fastMode')).toBe('false')
})

it('keeps Fast on across a model switch while support discovery is transient', async () => {
Expand Down Expand Up @@ -346,8 +347,8 @@ describe('Claude structured Fast mode', () => {
).resolves.toMatchObject({ model: 'haiku', fastMode: 'false' })
expect(session.reportedOptions.fastMode).toBe(true)
expect(session.confirmedOptions.has('fastMode')).toBe(false)
expect(session.reusableOptions.get('model')).toBe('haiku')
expect(session.reusableOptions.has('fastMode')).toBe(false)
expect(session.appliedInputOptions.get('model')).toBe('haiku')
expect(session.appliedInputOptions.has('fastMode')).toBe(false)
})

it('treats an unrecognized provider disabled reason as unavailable', async () => {
Expand Down
Loading
Loading