Skip to content

armgit / orca

Public Imported from GitHub
0

Orca is the place for working with a fleet of agents (e.g. Grok Bot, Claude Code). Run any coding agent with your own subscription. Available on desktop, mobile and remote runtime.

fix(pi): the thinking menu before the first message matches the chat's (#34592)

Brennan Bensonb578e3012e3a
diff --git a/mobile/src/session/use-mobile-structured-agent-options.first-frame.test.ts b/mobile/src/session/use-mobile-structured-agent-options.first-frame.test.ts
index 093ace91992..de9f3f90c8b 100644
--- a/mobile/src/session/use-mobile-structured-agent-options.first-frame.test.ts
+++ b/mobile/src/session/use-mobile-structured-agent-options.first-frame.test.ts
@@ -42,7 +42,7 @@ function modelChoices(snapshot: readonly SessionOptionDescriptor[]): string[] {
return model?.kind.type === 'select' ? model.kind.choices.map((choice) => choice.value) : []
}
-type Props = { rpc: RpcClient; fence: number }
+type Props = { rpc: RpcClient; fence: number; agent?: 'pi' | 'codex' }
async function mount(initial: Props) {
const frames: string[][] = []
@@ -52,7 +52,7 @@ async function mount(initial: Props) {
let latest!: ReturnType<typeof useMobileStructuredAgentOptions>
function Probe(props: Props): null {
const options = useMobileStructuredAgentOptions({
- agent: 'codex',
+ agent: props.agent ?? 'codex',
client: props.rpc,
sessionId: 'session-1',
enabled: true,
@@ -91,6 +91,29 @@ async function mount(initial: Props) {
}
describe('the phone picker’s first frame', () => {
+ it('projects a restored Pi off to the precise supported selection without offering off', async () => {
+ const row = {
+ id: 'openai/gpt-5',
+ label: 'GPT-5',
+ isDefault: false,
+ efforts: ['minimal', 'low', 'medium', 'high'].map((value) => ({ value, label: value }))
+ }
+ const rpc = client(
+ async () => ({ origin: 'probe', fetchedAt: 1, models: [row] }),
+ async () => ({
+ models: [row],
+ listedModelIds: [row.id],
+ current: { model: row.id, effort: 'off', defaulted: [] }
+ })
+ )
+ const harness = await mount({ rpc, fence: 1, agent: 'pi' })
+ expect(harness.snapshot().find((entry) => entry.id === 'effort')).toMatchObject({
+ settable: true,
+ kind: { currentValue: 'minimal', choices: row.efforts }
+ })
+ await harness.unmount()
+ })
+
it('shows the quiet placeholder, never the built-in list, until the host answers', async () => {
let answer!: (value: AgentSessionModelCatalogResult) => void
const rpc = client(() => new Promise((resolve) => (answer = resolve)))
diff --git a/mobile/src/session/use-mobile-structured-agent-options.test-fixture.ts b/mobile/src/session/use-mobile-structured-agent-options.test-fixture.ts
index 9f963900b08..e9ea529de6a 100644
--- a/mobile/src/session/use-mobile-structured-agent-options.test-fixture.ts
+++ b/mobile/src/session/use-mobile-structured-agent-options.test-fixture.ts
@@ -109,14 +109,17 @@ type MutateCall = { method: string; fields: Record<string, unknown> }
// Use an untyped mock: a concrete fixture cannot satisfy arbitrary TValue from the generic mutation caller.
function recordingMutate(
- next: (call: number) => Promise<StructuredAgentSessionMutationResult<AgentSessionOptionResult>>
+ next: (
+ call: number,
+ fields: Record<string, unknown>
+ ) => Promise<StructuredAgentSessionMutationResult<AgentSessionOptionResult>>
) {
const calls: MutateCall[] = []
const mock = vi.fn()
mock.mockImplementation(
(method: string, _fingerprintMethod: string, fields: Record<string, unknown>) => {
calls.push({ method, fields })
- return next(calls.length - 1)
+ return next(calls.length - 1, fields)
}
)
const mutate: StructuredAgentSessionMutate = mock
diff --git a/mobile/src/session/use-mobile-structured-agent-options.test.ts b/mobile/src/session/use-mobile-structured-agent-options.test.ts
index 8a2f6b02bb4..1eeb413620f 100644
--- a/mobile/src/session/use-mobile-structured-agent-options.test.ts
+++ b/mobile/src/session/use-mobile-structured-agent-options.test.ts
@@ -710,3 +710,54 @@ it('refuses a typed literal at an unresolved fence and accepts it when that fenc
expect(calls).toHaveLength(1)
await view.unmount()
})
+
+import type { PiRefreshFixtureModule } from '../../../src/shared/structured-agent-session-option-refresh.test-fixture-contract'
+const { piOptionRefreshContract } = await vi.importActual<PiRefreshFixtureModule>(
+ '../../../src/main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture'
+)
+
+describe('Pi catalog refresh completion', () => {
+ piOptionRefreshContract(
+ async (host) => {
+ const first = optionsClient(
+ () => host.options(),
+ () => host.catalog()
+ )
+ const second = optionsClient(
+ () => host.options(),
+ () => host.catalog()
+ )
+ const { mutate } = recordingMutate(async (_call, fields) => {
+ if (typeof fields.value !== 'string') {
+ throw new Error('missing effort')
+ }
+ return accepted(await host.acceptEffort(fields.value), true)
+ })
+ const harness = await mountOptions({
+ ...BASE,
+ agent: 'pi',
+ sendSelection: true,
+ sessionId: host.record.sessionId,
+ client: first.client,
+ mutate
+ })
+ return {
+ snapshot: () => harness.current().optionSnapshot,
+ capture: () => harness.current().sendSelection().selection,
+ demand: () => harness.current().optionSurface.demandModelCatalog?.(),
+ pick: (value) => harness.current().setStructuredOption('effort', value),
+ replace: async (fence, otherHost) =>
+ harness.rerender({ fence, client: otherHost ? second.client : first.client }),
+ close: () => harness.unmount()
+ }
+ },
+ async (work) => {
+ await act(async () => {
+ work()
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ await settle()
+ }
+ )
+})
diff --git a/mobile/src/session/use-mobile-structured-option-state.ts b/mobile/src/session/use-mobile-structured-option-state.ts
index 8e5b580b809..348750c5792 100644
--- a/mobile/src/session/use-mobile-structured-option-state.ts
+++ b/mobile/src/session/use-mobile-structured-option-state.ts
@@ -121,7 +121,8 @@ export function useMobileStructuredOptionState(args: {
...previous,
record: cloneStructuredAgentSessionOptionRecord(previous.record),
pendingId: null,
- reportedPermissionMode: undefined
+ reportedPermissionMode: undefined,
+ reportedEffort: undefined
}
: seeded
// Keep the chat’s mode visible through provider restarts.
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-option-actual.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-option-actual.test-fixture.ts
new file mode 100644
index 00000000000..ecaac363055
--- /dev/null
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-option-actual.test-fixture.ts
@@ -0,0 +1,119 @@
+import {
+ PiRpcOptionObservations,
+ applyPiRpcSessionOption,
+ type PiRpcOptionProof
+} from '../../pi/rpc-options'
+import { captureStructuredExecutionOptions } from './structured-agent-session-execution-options'
+import { StructuredAgentRegistry } from './structured-agent-registry'
+import { PI_RPC_AGENT } from '../../pi/rpc-agent-definition'
+import { PiRpcSessionAdapter } from '../../pi/rpc-session-adapter'
+import { createStructuredAgentSessionLogger } from './structured-agent-session-logger'
+import { expect, it } from 'vitest'
+import type { piOptionRefreshHost } from './structured-agent-session-option-refresh.test-fixture'
+import type {
+ PiRefreshHarness,
+ PiRefreshMount
+} from '../../../shared/structured-agent-session-option-refresh.test-fixture-contract'
+
+const precise = ['off', 'minimal', 'low', 'high', 'xhigh'].map((value) => ({ value, label: value }))
+const effort = (view: PiRefreshHarness) => view.snapshot().find((entry) => entry.id === 'effort')
+
+export function piOptionActualContract(
+ makeHost: typeof piOptionRefreshHost,
+ mount: PiRefreshMount,
+ flush: (work: () => void) => Promise<void>
+): void {
+ it('keeps cold matched actual display separate from raw capture through equal picks and context replacement', async () => {
+ const host = makeHost()
+ host.record.options.effort = 'off'
+ const proof: PiRpcOptionProof = { current: new Map(), writes: new Map() }
+ const setters: string[] = []
+ const rpc = {
+ request: async (command: string) => {
+ setters.push(command)
+ return {}
+ }
+ }
+ await applyPiRpcSessionOption(rpc, new Map(), 'model', host.record.options.model, {}, proof)
+ await applyPiRpcSessionOption(rpc, new Map(), 'effort', 'off', {}, proof)
+ const observations = new PiRpcOptionObservations(proof, () => true)
+ const observe = (effort: string) => {
+ observations.prepare()({
+ models: host.home.models,
+ current: {
+ model: host.record.options.model,
+ effort,
+ confirmed: ['model', 'effort']
+ }
+ })
+ host.live = observations.read()
+ }
+ observe('minimal')
+ const answer = await host.read()
+ expect(answer.current).toMatchObject({ effort: 'off', reportedEffort: 'minimal' })
+ expect(answer.current.confirmed).not.toContain('effort')
+ host.hostReads = 0
+ const view = await mount(host)
+ expect(effort(view)).toMatchObject({
+ valueSource: 'reported',
+ kind: { currentValue: 'minimal', choices: precise }
+ })
+ expect(view.capture()?.effort).toBe('off')
+ observe('low')
+ await flush(() => host.initialCatalog.resolve(host.home))
+ await flush(() => host.finish(0))
+ expect(effort(view)).toMatchObject({
+ valueSource: 'reported',
+ kind: { currentValue: 'low', choices: precise }
+ })
+ await flush(() => {
+ void view.pick('off')
+ })
+ expect(effort(view)?.valueSource).not.toBe('reported')
+ expect(view.capture()?.effort).toBe('off')
+ await flush(() => host.finish(1))
+ expect(host.requests.length).toBeLessThanOrEqual(3)
+ if (host.requests.length === 3) {
+ await flush(() => host.finish(2))
+ }
+ expect(effort(view)?.kind.currentValue).toBe('low')
+ const frozen = view.capture()!
+ host.record.options.effort = 'high'
+ const accepted = captureStructuredExecutionOptions(
+ {
+ agent: 'pi',
+ agents: new StructuredAgentRegistry([
+ {
+ definition: PI_RPC_AGENT,
+ adapter: new PiRpcSessionAdapter({
+ logger: createStructuredAgentSessionLogger(),
+ onLifecycle: () => {},
+ onSettled: () => {},
+ resolveLaunch: async () => {
+ throw new Error('capture does not launch')
+ }
+ })
+ }
+ ]),
+ persistedOptions: host.record.options
+ },
+ undefined,
+ frozen
+ )
+ expect(accepted).toMatchObject({ options: { effort: 'off' } })
+ expect(proof.current.get('effort')).toBe('off')
+ expect(setters).toEqual(['set_model', 'set_thinking_level'])
+ host.record.options.effort = 'off'
+ host.live = {
+ models: host.home.models,
+ current: { model: host.record.options.model, effort: 'off' }
+ }
+ const replacement = host.requests.length
+ await view.replace(3)
+ expect(effort(view)?.kind.currentValue).not.toBe('low')
+ await flush(() => host.finish(replacement))
+ expect(effort(view)?.valueSource).not.toBe('reported')
+ expect(view.capture()?.effort).toBe('off')
+ await view.close()
+ })
+}
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-option-models.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-option-models.ts
index d330a407554..72b98147b9b 100644
--- a/src/main/native-chat/agent-session-wire/structured-agent-session-option-models.ts
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-option-models.ts
@@ -13,6 +13,8 @@ export type StructuredAgentSessionOptionProjection = {
}
export type StructuredAgentSessionLiveOptions = AgentSessionOptionsResult & {
+ /** Child/request-scoped actual or raw future intent; never serialized as a callback. */
+ projectCurrent?: (saved: Readonly<Record<string, string>>) => AgentSessionOptionsResult['current']
catalogListing?: AgentModelCatalogLiveListing
/** The running CLI cannot change effort mid-chat, whatever its catalog lists. */
effortFixed?: true
@@ -67,3 +69,15 @@ export function structuredAgentSessionCapabilityView(
)
}
}
+
+export function confirmedCurrentOptions(
+ current: AgentSessionOptionsResult['current'],
+ reported: AgentSessionOptionsResult['current'],
+ confirmed = reported.confirmed
+): AgentSessionOptionsResult['current']['confirmed'] {
+ return confirmed?.filter((key) =>
+ key === 'model' || key === 'effort' || key === 'fastMode' || key === 'serviceTier'
+ ? current[key] === reported[key]
+ : false
+ )
+}
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture.ts
new file mode 100644
index 00000000000..89fbcf76315
--- /dev/null
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture.ts
@@ -0,0 +1,293 @@
+import { expect, it } from 'vitest'
+import { piOptionActualContract } from './structured-agent-session-option-actual.test-fixture'
+import type {
+ AgentSessionModelCatalogResult,
+ AgentSessionOptionResult,
+ AgentSessionOptionsResult
+} from '../../../shared/agent-session-wire'
+import type {
+ PiRefreshHarness,
+ PiRefreshMount
+} from '../../../shared/structured-agent-session-option-refresh.test-fixture-contract'
+import type { AgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service'
+import type { StructuredAgentSessionMutationContext } from './structured-agent-session-host-mutations'
+import type { StructuredAgentSessionLiveOptions } from './structured-agent-session-option-models'
+import {
+ hostTestRestingOptionsRecord,
+ hostTestRestingOptionsJournal,
+ hostTestOptionsReadStore
+} from './structured-agent-session-host-test-data'
+import { readStructuredAgentSessionOptions } from './structured-agent-session-options-read'
+
+function deferred<T>() {
+ let resolve!: (value: T) => void
+ let reject!: (reason: Error) => void
+ const promise = new Promise<T>((accept, refuse) => {
+ resolve = accept
+ reject = refuse
+ })
+ return { promise, resolve, reject }
+}
+
+const levels = (values: string[]) => values.map((value) => ({ value, label: value }))
+const gap = levels(['off', 'minimal', 'low', 'xhigh'])
+const precise = levels(['off', 'minimal', 'low', 'high', 'xhigh'])
+
+/** Exercise the host's actual rest/live reader; only transport completion is held. */
+export function piOptionRefreshHost(sessionId = 'session-1') {
+ const record = {
+ ...hostTestRestingOptionsRecord(sessionId),
+ provider: 'pi',
+ options: { model: 'openai/model', effort: 'medium' }
+ }
+ const row = { id: record.options.model, label: 'Model', isDefault: false, efforts: gap }
+ let live: StructuredAgentSessionLiveOptions | null = null
+ let modelCatalog: Pick<AgentModelCatalogService, 'read'> | null = null
+ const requests: ReturnType<typeof deferred<AgentSessionOptionsResult>>[] = []
+ const host = {
+ record,
+ models: [row],
+ get live(): StructuredAgentSessionLiveOptions | null {
+ return live
+ },
+ set live(value: StructuredAgentSessionLiveOptions | null) {
+ live = value
+ },
+ get modelCatalog(): Pick<AgentModelCatalogService, 'read'> | null {
+ return modelCatalog
+ },
+ set modelCatalog(value: Pick<AgentModelCatalogService, 'read'> | null) {
+ modelCatalog = value
+ },
+ hostReads: 0,
+ catalogReads: 0,
+ passiveReads: 0,
+ requests,
+ initialCatalog: deferred<AgentSessionModelCatalogResult>(),
+ catalogCalls: 0,
+ blockWrite: false,
+ write: deferred<void>(),
+ acceptEffort: async (value: string): Promise<AgentSessionOptionResult> => {
+ if (host.blockWrite) {
+ await host.write.promise
+ }
+ record.options.effort = value
+ return { key: 'effort', value, options: { ...record.options } }
+ },
+ home: {
+ origin: 'probe',
+ fetchedAt: 2,
+ models: [{ ...row, efforts: precise }]
+ } satisfies AgentSessionModelCatalogResult,
+ catalog: (): Promise<AgentSessionModelCatalogResult> =>
+ ++host.catalogCalls === 1 ? host.initialCatalog.promise : Promise.resolve(host.home),
+ read: async (): Promise<AgentSessionOptionsResult> => {
+ host.hostReads += 1
+ const conversation = {
+ child: host.live ? { fence: 2, phase: 'ready' } : null,
+ params: { provider: 'pi' },
+ journal: hostTestRestingOptionsJournal()
+ }
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: the real reader accesses only these injected ports; no provider process is launched.
+ const context = {
+ deps: {
+ adapter: {
+ readOptions: async () => {
+ host.passiveReads += 1
+ return host.live
+ }
+ },
+ agents: { definition: () => null, capabilities: () => null },
+ store: hostTestOptionsReadStore(() => record),
+ modelCatalog: host.modelCatalog ?? {
+ read: async (params: { savedOnly?: boolean }) => {
+ expect(params.savedOnly).toBe(true)
+ host.catalogReads += 1
+ return { origin: 'probe', fetchedAt: 1, models: host.models }
+ }
+ }
+ },
+ serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
+ openConversation: async () => conversation,
+ conversation: async () => conversation
+ } as unknown as StructuredAgentSessionMutationContext
+ return readStructuredAgentSessionOptions(context, sessionId, { readsWithoutModel: true })
+ },
+ options: (): Promise<AgentSessionOptionsResult> => {
+ const answer = host.read()
+ if (host.hostReads === 1) {
+ return answer
+ }
+ const request = deferred<AgentSessionOptionsResult>()
+ host.requests.push(request)
+ // Sample at dispatch, rather than giving an old request the state at its eventual completion.
+ return Promise.all([answer, request.promise]).then(([sampled]) => sampled)
+ },
+ finish: (index: number): void => host.requests[index]!.resolve({ models: [], current: {} })
+ }
+ return host
+}
+
+function effort(view: PiRefreshHarness) {
+ return view.snapshot().find((entry) => entry.id === 'effort')
+}
+function assertView(view: PiRefreshHarness, selected: string, choices = gap) {
+ expect(effort(view)).toMatchObject({
+ settable: true,
+ kind: { currentValue: selected, choices }
+ })
+ expect(effort(view)?.valueSource).not.toBe('reported')
+}
+
+export function piOptionRefreshContract(
+ mount: PiRefreshMount,
+ flush: (work: () => void) => Promise<void>
+): void {
+ piOptionActualContract(piOptionRefreshHost, mount, flush)
+ it('completes a catalog burst through the host with one active and one trailing read per owner at 6 and 60 owners', async () => {
+ const counts: number[] = []
+ for (const population of [6, 60]) {
+ const hosts = Array.from({ length: population }, (_, index) =>
+ piOptionRefreshHost(`refresh-${index}`)
+ )
+ const views: PiRefreshHarness[] = []
+ for (const host of hosts) {
+ views.push(await mount(host))
+ }
+ for (const view of views) {
+ assertView(view, 'xhigh')
+ expect(view.capture()?.effort).toBe('medium')
+ }
+ await flush(() => hosts.forEach((host) => host.initialCatalog.resolve(host.home)))
+ expect(hosts.map((host) => host.requests.length)).toEqual(Array(population).fill(1))
+ for (let burst = 0; burst < 3; burst += 1) {
+ await flush(() => views.forEach((view) => view.demand()))
+ }
+ for (const view of views) {
+ assertView(view, 'xhigh')
+ }
+ expect(
+ hosts.every((host) => host.hostReads === 2 && host.record.options.effort === 'medium')
+ ).toBe(true)
+ hosts.forEach((host) => {
+ host.models = host.home.models
+ })
+ await flush(() => hosts.forEach((host) => host.finish(0)))
+ expect(hosts.every((host) => host.requests.length === 2)).toBe(true)
+ for (const view of views) {
+ assertView(view, 'xhigh')
+ }
+ await flush(() => hosts.forEach((host) => host.finish(1)))
+ for (const view of views) {
+ assertView(view, 'high', precise)
+ }
+ counts.push(hosts.reduce((count, host) => count + host.hostReads, 0))
+ expect(
+ hosts.every(
+ (host) => host.hostReads === 3 && host.catalogReads <= 6 && host.passiveReads === 0
+ )
+ ).toBe(true)
+ expect(hosts.every((host) => host.record.options.effort === 'medium')).toBe(true)
+ for (const view of views) {
+ await view.close()
+ }
+ }
+ expect(counts).toEqual([18, 180])
+ })
+
+ it('releases failed reads, retains last-good without an invented retry, and drops queued work on teardown', async () => {
+ const host = piOptionRefreshHost()
+ const view = await mount(host)
+ await flush(() => host.initialCatalog.resolve(host.home))
+ await flush(() => host.requests[0]!.reject(new Error('read failed')))
+ assertView(view, 'xhigh')
+ expect(host.hostReads).toBe(2)
+ await flush(() => {})
+ expect(host.hostReads).toBe(2)
+ await flush(() => view.demand())
+ await flush(() => view.demand())
+ host.models = host.home.models
+ await flush(() => host.requests[1]!.reject(new Error('read timeout')))
+ expect(host.requests).toHaveLength(3)
+ await flush(() => host.finish(2))
+ assertView(view, 'high', precise)
+ expect(host.record.options.effort).toBe('medium')
+ await flush(() => view.demand())
+ await flush(() => view.demand())
+ const dispatched = host.hostReads
+ await view.close()
+ await flush(() => host.finish(3))
+ expect(host.hostReads).toBe(dispatched)
+ })
+
+ it('preserves a newer accepted High across an old answer, write parking, and a live-home refresh', async () => {
+ const host = piOptionRefreshHost()
+ host.models = host.home.models
+ const view = await mount(host)
+ await flush(() => host.initialCatalog.resolve(host.home))
+ host.blockWrite = true
+ await flush(() => {
+ void view.pick('high')
+ })
+ await flush(() => view.demand())
+ await flush(() => host.finish(0))
+ // Reads may complete while a controller write is pending; the raw overlay still wins.
+ expect(host.requests).toHaveLength(2)
+ expect(view.capture()?.effort).toBe('high')
+ await flush(() => host.write.resolve())
+ assertView(view, 'high', precise)
+ expect(host.record.options.effort).toBe('high')
+ await flush(() => host.finish(1))
+ expect(host.requests).toHaveLength(3)
+ // A held live answer carries future raw High, with no claim that the provider applied it.
+ host.live = {
+ models: [{ ...host.models[0]!, efforts: precise }],
+ current: { model: host.record.options.model, effort: 'high' }
+ }
+ await flush(() => host.finish(2))
+ assertView(view, 'high', precise)
+ host.home = { ...host.home, models: [{ ...host.models[0]!, efforts: levels(['minimal']) }] }
+ await flush(() => view.demand())
+ await flush(() => host.finish(3))
+ assertView(view, 'high', precise)
+ expect(host.passiveReads).toBe(1)
+ await view.close()
+ })
+
+ it('fences old and queued answers across child replacement and host/context replacement', async () => {
+ const host = piOptionRefreshHost()
+ const view = await mount(host)
+ await flush(() => host.initialCatalog.resolve(host.home))
+ await flush(() => view.demand())
+ host.models = host.home.models
+ host.live = {
+ models: host.models,
+ current: { model: host.record.options.model, effort: 'medium' }
+ }
+ await view.replace(2)
+ const afterReplacement = host.hostReads
+ await flush(() => host.finish(0))
+ expect(host.hostReads).toBe(afterReplacement)
+ await view.replace(3)
+ const beforeOldChild = view.snapshot()
+ await flush(() => host.finish(1))
+ expect(view.snapshot()).toEqual(beforeOldChild)
+ // Phase equality is not child identity; then live-to-rest also changes host/client.
+ host.live = null
+ await view.replace(4, true)
+ const afterHostChange = host.hostReads
+ const beforeOldHost = view.snapshot()
+ await flush(() => host.finish(2))
+ expect(host.hostReads).toBe(afterHostChange)
+ expect(view.snapshot()).toEqual(beforeOldHost)
+ await flush(() => host.finish(3))
+ // A new host's catalog completion can supersede its first options read once.
+ expect(host.requests.length).toBeLessThanOrEqual(5)
+ if (host.requests.length === 5) {
+ await flush(() => host.finish(4))
+ }
+ assertView(view, 'high', precise)
+ expect(host.record.options.effort).toBe('medium')
+ await view.close()
+ })
+}
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read-scaling.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read-scaling.test.ts
new file mode 100644
index 00000000000..c56e09f39b6
--- /dev/null
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read-scaling.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest'
+import { agentSessionConversationView } from '../../../shared/agent-session-conversation-view'
+import type { AgentSessionModelOption } from '../../../shared/agent-session-wire'
+import { createAgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service'
+import { AgentModelCatalogStore } from '../agent-model-catalog/agent-model-catalog-store'
+import { PiRpcOptionObservations, type PiRpcOptionProof } from '../../pi/rpc-options'
+import { piOptionRefreshHost } from './structured-agent-session-option-refresh.test-fixture'
+
+const SESSION = 'session-1'
+describe('host options row work', () => {
+ it('bounds resting and live host row reads without per-chat discovery at 61 and 610 models', async () => {
+ const counts: number[][] = []
+ for (const size of [61, 610]) {
+ const host = piOptionRefreshHost()
+ const record = host.record
+ record.options = { model: `model-${size - 1}`, effort: 'off' }
+ const models = Array.from({ length: size }, (_, index) => ({
+ id: `model-${index}`,
+ label: 'Model',
+ isDefault: false,
+ efforts: [{ value: 'minimal', label: 'Minimal' }]
+ }))
+ const probe = vi.fn(async () => ({ models, origin: 'probe' as const, complete: true }))
+ const service = createAgentModelCatalogService({
+ store: new AgentModelCatalogStore(),
+ getRecord: () => record,
+ getConversation: () => agentSessionConversationView(record),
+ drivesRecord: () => true,
+ resolveAccountHome: async () => record.accountHome,
+ recordWorkspacePath: async () => '/workspace',
+ probes: { pi: probe }
+ })
+ await service.read({
+ agent: 'pi',
+ sessionId: SESSION,
+ inSessionWorkspace: true,
+ waitForListing: true
+ })
+ let rowReads = 0
+ const countRows = (rows: AgentSessionModelOption[]) =>
+ rows.map(({ id, ...row }) => ({
+ ...row,
+ get id() {
+ rowReads++
+ return id
+ }
+ }))
+ const read = service.read.bind(service)
+ const reads = vi.spyOn(service, 'read').mockImplementation(async (params) => {
+ const answer = await read(params)
+ return answer.origin === 'unknown'
+ ? answer
+ : {
+ ...answer,
+ models: countRows(answer.models)
+ }
+ })
+ const measured: number[] = []
+ for (const live of [false, true]) {
+ rowReads = 0
+ host.modelCatalog = service
+ host.live = live
+ ? {
+ models: countRows(models),
+ current: { model: record.options.model, effort: 'minimal' }
+ }
+ : null
+ const answer = await host.read()
+ expect(answer.current.effort).toBe('off')
+ expect(rowReads).toBeGreaterThanOrEqual(size)
+ expect(rowReads).toBeLessThanOrEqual(12 * size)
+ measured.push(rowReads)
+ }
+ counts.push(measured)
+ expect(reads).toHaveBeenCalledTimes(2)
+ expect(reads.mock.calls.every(([params]) => params.savedOnly === true)).toBe(true)
+ expect(probe).toHaveBeenCalledTimes(1)
+ service.stop()
+ }
+ for (const index of [0, 1]) {
+ expect(counts[1]![index]).toBeLessThanOrEqual(10 * counts[0]![index]!)
+ }
+ })
+})
+
+it('pairs the latest saved input with its report only after the resting read completes', async () => {
+ const host = piOptionRefreshHost()
+ host.record.options.effort = 'off'
+ const proof: PiRpcOptionProof = {
+ current: new Map([
+ ['model', host.record.options.model],
+ ['effort', 'off']
+ ]),
+ writes: new Map()
+ }
+ const observations = new PiRpcOptionObservations(proof, () => true)
+ observations.prepare()({
+ models: host.models,
+ current: { model: host.record.options.model, effort: 'minimal', confirmed: ['model', 'effort'] }
+ })
+ host.live = observations.read()
+ const entered = Promise.withResolvers<void>()
+ const catalog =
+ Promise.withResolvers<Awaited<ReturnType<NonNullable<typeof host.modelCatalog>['read']>>>()
+ host.modelCatalog = {
+ read: () => {
+ entered.resolve()
+ return catalog.promise
+ }
+ }
+ const answer = host.read()
+ await entered.promise
+ host.record.options.effort = 'high'
+ catalog.resolve(host.home)
+ const result = await answer
+ expect(result.current.effort).toBe('high')
+ expect(result.current.reportedEffort).toBeUndefined()
+ expect(result.current.confirmed).not.toContain('effort')
+ expect(result).not.toHaveProperty('projectCurrent')
+ expect(result).not.toHaveProperty('effortFixed')
+})
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.test.ts
index 388b11566ba..043f9258657 100644
--- a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.test.ts
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.test.ts
@@ -9,6 +9,7 @@ import { readLiveCodexSessionOptions } from '../../codex/codex-structured-sessio
import { optionSession } from '../../codex/codex-structured-option-session.test-fixture'
import { CodexAppServerRequestError } from '../../codex/app-server/codex-app-server-request-error'
import { structuredAgentSessionDrawnValues } from '../../../shared/structured-agent-session-option-snapshot'
+
import { structuredAgentSessionCapabilityView } from './structured-agent-session-option-models'
import { claudeFallbackModelOptions } from '../../claude/claude-structured-session-options'
import {
@@ -23,7 +24,6 @@ import {
createStructuredAgentSessionOptionState
} from '../../../shared/structured-agent-session-options'
import type { StructuredAgentSessionLiveOptions } from './structured-agent-session-adapter'
-
import { describe, expect, it, vi } from 'vitest'
import type { AgentSessionRecord } from '../../../shared/agent-session-record'
import {
@@ -35,7 +35,10 @@ import {
import type { AgentJournalItemBody } from '../../../shared/agent-session-journal-types'
import { claudeProviderHandle } from '../../../shared/agent-session-provider-handle-encoding'
import type { AgentSessionModelOption } from '../../../shared/agent-session-wire'
-import { createAgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service'
+import {
+ createAgentModelCatalogService,
+ type AgentModelCatalogService
+} from '../agent-model-catalog/agent-model-catalog-service'
import {
AgentModelCatalogStore,
type AgentModelCatalogSuccess
@@ -260,7 +263,8 @@ describe('a chat at rest, read by the host', () => {
wroteBeforeOpen = false,
models: AgentSessionModelOption[] | null = listed,
verified = true,
- liveOptions?: StructuredAgentSessionLiveOptions
+ liveOptions?: StructuredAgentSessionLiveOptions,
+ modelCatalog: Pick<AgentModelCatalogService, 'read'> = catalog(models, verified)
) {
const record = { ...restingRecord(), ...facts }
const resting = {
@@ -274,7 +278,7 @@ describe('a chat at rest, read by the host', () => {
adapter: liveOptions ? { readOptions: async () => liveOptions } : {},
agents: claudeAndCodexAgents(),
store: hostTestOptionsReadStore(() => record),
- modelCatalog: catalog(models, verified)
+ modelCatalog
},
serialize: (_sessionId: string, task: () => Promise<unknown>) => task(),
openConversation: async () => resting,
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.ts
index baf1c799b2e..9f4bd16007e 100644
--- a/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.ts
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-options-read.ts
@@ -14,6 +14,7 @@ import type { AgentSessionAcceptedInputSources } from '../../../shared/agent-ses
import { journalOpenReadRefusal } from '../agent-session-journal/journal-open-failure'
import type { StructuredAgentSessionLiveOptions } from './structured-agent-session-adapter'
import {
+ confirmedCurrentOptions,
structuredAgentSessionCapabilityView,
type StructuredAgentSessionRestingOptions as RestingOptions
} from './structured-agent-session-option-models'
@@ -75,7 +76,7 @@ export async function readStructuredAgentSessionOptions(
(rested ??= await readStructuredAgentSessionOptionsAtRest(context.deps, sessionId, reader))
let options: Omit<AgentSessionOptionsResult, 'rewind'>
if (live) {
- const { catalogListing, effortFixed: _fixed, ...answer } = live
+ const { catalogListing, effortFixed: _fixed, projectCurrent: _project, ...answer } = live
options = answer
// Fill missing live listings from saved catalog state; absent records keep the child’s answer.
if (!catalogListing && !answer.listedModelIds && store.getConversation(sessionId)) {
@@ -88,16 +89,17 @@ export async function readStructuredAgentSessionOptions(
}
// Earlier reads may have closed/reopened the handle.
const session = await context.conversation(sessionId)
- const record = store.getConversation(sessionId)
- const phase = record?.rewind?.phase
const agent = session.params.provider
const capabilities = agents.capabilities(agent)
const floor = session.journal.context.floor()
const contextFloor = floor ? { contextFloor: floor } : {}
+ const restingOptions = await atRest()
+ const resting = live ? restingOptions : null
+ const record = store.getConversation(sessionId)
const permissionMode = record
? structuredAgentSessionImmediatePermission(context.deps, record)
: null
- const resting = live ? await atRest() : null
+ const phase = record?.rewind?.phase
const selected = resting ?? options
const independent = independentAgentModelCatalog(agent)
const displayDefault =
@@ -108,6 +110,8 @@ export async function readStructuredAgentSessionOptions(
: undefined
const saved = record?.options ?? {}
const model = saved.model ?? (options.current.model || selected.current.model || displayDefault)
+ const projected = live?.projectCurrent?.({ ...saved, ...(model ? { model } : {}) })
+ const reportedEffort = projected?.confirmed?.includes('effort') ? projected.effort : undefined
const current = {
...selected.current,
...options.current,
@@ -145,13 +149,9 @@ export async function readStructuredAgentSessionOptions(
if (saved.fastMode === undefined && selected.current.fastMode === false) {
acceptedInputSources.fastMode = 'policy'
}
- const confirmed = options.current.confirmed?.filter((key) =>
- key === 'model' || key === 'effort' || key === 'fastMode' || key === 'serviceTier'
- ? current[key] === options.current[key]
- : false
- )
+ const confirmed = confirmedCurrentOptions(current, projected ?? options.current)
if (independent) {
- const { inventory, fallback, listedModelIds } = await atRest()
+ const { inventory, fallback, listedModelIds } = restingOptions
if (saved.model === undefined && current.model && inventory.origin !== 'unknown') {
current.model =
inventory.models.find(
@@ -192,6 +192,7 @@ export async function readStructuredAgentSessionOptions(
current: {
...current,
acceptedInputSources,
+ ...(reportedEffort !== undefined ? { reportedEffort } : {}),
defaulted,
confirmed,
...(options.current.fastModeState ? { fastModeState: options.current.fastModeState } : {}),
diff --git a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts
index cf722b02911..1f99738b249 100644
--- a/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts
+++ b/src/main/native-chat/agent-session-wire/structured-agent-session-queued-pause-lift.test.ts
@@ -1,3 +1,13 @@
+import { structuredAgentSessionSeedCatalog } from '../../../shared/structured-agent-session-seed-catalog'
+import {
+ applyStructuredAgentSessionOptions,
+ createStructuredAgentSessionOptionState
+} from '../../../shared/structured-agent-session-options'
+import {
+ structuredAgentSessionMessageSelection,
+ structuredAgentSessionShownSnapshot
+} from '../../../shared/structured-agent-session-option-view'
+import { piOptionRefreshHost } from './structured-agent-session-option-refresh.test-fixture'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { AgentSessionJournal } from '../agent-session-journal/journal-store'
import { JournalStopAcceptor } from '../agent-session-journal/journal-stop-acceptance'
@@ -19,6 +29,9 @@ import {
import { openRigTurnFor } from './structured-agent-session-queued-rig-turn.test-fixture'
import { sameQueuePause } from './structured-agent-session-queued-publication'
import { structuredQueuePauses } from './structured-agent-session-queued-pause'
+import { createAgentModelCatalogService } from '../agent-model-catalog/agent-model-catalog-service'
+import { AgentModelCatalogStore } from '../agent-model-catalog/agent-model-catalog-store'
+import { agentModelCatalogFingerprintForRecord } from '../agent-model-catalog/agent-model-catalog-fingerprint'
import { createStructuredSessionObservationClock } from './structured-agent-session-observation-clock.test-fixture'
@@ -86,6 +99,118 @@ async function handedOverUserSend(text: string): Promise<string> {
describe("a Stop's queue pause", () => {
installRigLifecycleHooks()
+ it('keeps accepted execution and fingerprint exact through catalog refresh, restart, later picks and replay', async () => {
+ const working = await rig.workingSend()
+ const record = rig.store.getRecord(HOST_TEST_SESSION)!
+ const catalogStore = new AgentModelCatalogStore()
+ const models = (efforts: string[]) => [
+ {
+ id: 'openai/model',
+ label: 'GPT-5',
+ isDefault: false,
+ efforts: efforts.map((value) => ({ value, label: value }))
+ }
+ ]
+ const catalog = createAgentModelCatalogService({
+ store: catalogStore,
+ getRecord: (id) => rig.store.getRecord(id) ?? undefined,
+ getConversation: (id) => rig.store.getConversation(id) ?? undefined,
+ drivesRecord: () => true,
+ resolveAccountHome: async () => record.accountHome
+ })
+ await catalog.prepareSaved?.({
+ agent: record.provider,
+ sessionId: HOST_TEST_SESSION,
+ inSessionWorkspace: true
+ })
+ rig.host.deps.modelCatalog = catalog
+ rig.host.deps.adapter.readOptions = async () => ({ models: [], current: {} })
+ const key = agentModelCatalogFingerprintForRecord(record)
+ catalogStore.recordSuccess(
+ key,
+ record.provider,
+ {
+ models: models(['medium', 'high']),
+ origin: 'probe',
+ complete: true
+ },
+ 'discovery'
+ )
+ const pi = piOptionRefreshHost()
+ const seed = structuredAgentSessionSeedCatalog('pi')
+ const view = applyStructuredAgentSessionOptions(
+ createStructuredAgentSessionOptionState('pi', seed),
+ seed,
+ await pi.read()
+ )
+ expect(
+ structuredAgentSessionShownSnapshot(view).find(({ id }) => id === 'effort')?.kind.currentValue
+ ).toBe('xhigh')
+ const selection = structuredAgentSessionMessageSelection(view)
+ expect(selection).toEqual({ model: 'openai/model', effort: 'medium' })
+ const body = hostTestMessage('frozen medium')
+ const fields = {
+ body,
+ delivery: 'queue-if-active' as const,
+ selection
+ }
+ const params = {
+ ...fields,
+ envelope: rig.envelope(fields, 'agentSession.send', hostTestOperationId())
+ }
+ const queued = await rig.host.send(QUEUED_RIG_CALLER, params)
+ if (!queued.ok || !('queued' in queued.value)) {
+ throw new Error('expected queued receipt')
+ }
+ const id = queued.value.queued.messageId
+ const journal = rig.host.collaboratorsForTests().sessions.get(HOST_TEST_SESSION)!.journal
+ const frozen = { ...journal.queuedMessages.get(id) }
+ const refresh = vi.fn(async () => ({
+ models: models(['off', 'minimal', 'low', 'xhigh']),
+ origin: 'probe' as const,
+ complete: true
+ }))
+ await catalogStore.refresh(key, record.provider, refresh, () => true)
+ expect(refresh).toHaveBeenCalledTimes(1)
+ const refreshed = await rig.host.readOptions(HOST_TEST_SESSION)
+ expect(
+ refreshed.models
+ .find((row) => row.id === fields.selection.model)
+ ?.efforts.map((choice) => choice.value)
+ ).toEqual(['off', 'minimal', 'low', 'xhigh'])
+ expect(journal.queuedMessages.get(id)?.options).toEqual(fields.selection)
+ const pick = { key: 'effort', value: 'high' }
+ expect(
+ await rig.host.setOption(QUEUED_RIG_CALLER, {
+ ...pick,
+ envelope: rig.envelope(pick, 'agentSession.setOption', hostTestOperationId())
+ })
+ ).toMatchObject({ ok: true })
+ await rig.restartHostProcess()
+ rig.host.deps.modelCatalog = catalog
+ expect(await rig.host.send(QUEUED_RIG_CALLER, params)).toMatchObject({
+ ok: true,
+ replayed: true
+ })
+ await rig.settleAccepted(working, 'before-restart')
+ expect(await rig.sendNow(id)).toMatchObject({ ok: true })
+ await eventually(async () => {
+ const submitted = await rig.handoff(id)
+ expect(submitted?.options).toEqual(fields.selection)
+ const dispatched = rig.dispatch.mock.calls.find(
+ ([input]) => input.clientMessageId === submitted?.clientMessageId
+ )
+ expect(dispatched?.[0].executionOptions).toEqual(fields.selection)
+ })
+ const restored = rig.host
+ .collaboratorsForTests()
+ .sessions.get(HOST_TEST_SESSION)!
+ .journal.queuedMessages.get(id)
+ expect(restored?.fingerprint).toBe(frozen.fingerprint)
+ expect(restored?.options).toEqual(fields.selection)
+ catalog.stop()
+ })
+
it('outlives a user send the provider accepts and then refuses; a later send that starts lifts it', async () => {
const draftId = await stoppedDraft()
const refused = await handedOverUserSend('the start fails')
diff --git a/src/main/pi/pi-scripted-child.test-fixture.ts b/src/main/pi/pi-scripted-child.test-fixture.ts
index f1852ac9514..356570f9351 100644
--- a/src/main/pi/pi-scripted-child.test-fixture.ts
+++ b/src/main/pi/pi-scripted-child.test-fixture.ts
@@ -7,6 +7,18 @@ import type { ProviderProcessLaunch } from '../provider-process/provider-process
import type { ScriptedAgentChild } from '../runtime/structured-agent-scripted-child.test-fixture'
import type { PiRpcConnection } from './rpc-session'
+type PiScriptOptions = {
+ signedOut?: boolean
+ model?: {
+ provider: string
+ id: string
+ reasoning: boolean
+ thinkingLevelMap?: Record<string, string | null>
+ }
+ /** Recorded native responses for requested levels, rather than a second clamp implementation. */
+ appliedEfforts?: Readonly<Record<string, string>>
+}
+
class ScriptedPiConnection implements PiRpcConnection {
closed = false
rootVerdict: PiRpcConnection['rootVerdict'] = 'live'
@@ -18,7 +30,11 @@ class ScriptedPiConnection implements PiRpcConnection {
private readonly exitListeners = new Set<() => void>()
private firstStateRead = true
private streaming = false
- private model = { provider: 'scripted', id: 'model-1', reasoning: true }
+ private model: NonNullable<PiScriptOptions['model']> = {
+ provider: 'scripted',
+ id: 'model-1',
+ reasoning: true
+ }
private effort = 'medium'
constructor(
@@ -30,8 +46,11 @@ class ScriptedPiConnection implements PiRpcConnection {
private readonly onClosed: () => void,
number: number,
/** A Pi with no login runs the unknown provider and lists no model. */
- private readonly signedOut = false
+ private readonly signedOut = false,
+ private readonly options: PiScriptOptions = {},
+ private readonly inputs: { command: string; params: Record<string, unknown> }[] = []
) {
+ this.model = options.model ?? this.model
this.pid = 42_000 + number
const sessionIndex = launch.args.indexOf('--session')
this.file =
@@ -46,6 +65,7 @@ class ScriptedPiConnection implements PiRpcConnection {
throw new Error('Scripted Pi connection closed')
}
this.wire.push(command)
+ this.inputs.push({ command, params: { ...params } })
if (command === 'get_state') {
if (this.firstStateRead) {
this.firstStateRead = false
@@ -71,7 +91,7 @@ class ScriptedPiConnection implements PiRpcConnection {
return this.model
}
if (command === 'set_thinking_level' && typeof params.level === 'string') {
- this.effort = params.level
+ this.effort = this.options.appliedEfforts?.[params.level] ?? params.level
return {}
}
if (command === 'abort') {
@@ -85,6 +105,7 @@ class ScriptedPiConnection implements PiRpcConnection {
if (this.closed || frame.type !== 'prompt' || typeof frame.message !== 'string') {
throw new Error('Scripted Pi requires a live prompt')
}
+ this.inputs.push({ command: 'prompt', params: { message: frame.message, effort: this.effort } })
this.received.push(frame.message)
this.wire.push(`prompt:${frame.message}`)
if (this.signedOut) {
@@ -112,6 +133,10 @@ class ScriptedPiConnection implements PiRpcConnection {
}
}
+ setNativeEffort(level: string): void {
+ this.effort = level
+ }
+
releaseHandshake(): void {
if (!this.closed) {
this.handshake.resolve(this.state())
@@ -196,13 +221,16 @@ class ScriptedPiConnection implements PiRpcConnection {
export type ScriptedPiChild = ScriptedAgentChild & {
/** Every request command and prompt any spawn received, in order. */
wire(): readonly string[]
+ inputs(): readonly { command: string; params: Record<string, unknown> }[]
signIn(): void
+ setNativeEffort(level: string): void
}
-export const piScriptedChild = (options: { signedOut?: boolean } = {}): ScriptedPiChild => {
+export const piScriptedChild = (options: PiScriptOptions = {}): ScriptedPiChild => {
const children: ScriptedPiConnection[] = []
const received: string[] = []
const wire: string[] = []
+ const inputs: { command: string; params: Record<string, unknown> }[] = []
let resumed = 0
let closed = 0
let signedOut = options.signedOut ?? false
@@ -245,7 +273,9 @@ export const piScriptedChild = (options: { signedOut?: boolean } = {}): Scripted
closed += 1
},
children.length + 1,
- signedOut
+ signedOut,
+ options,
+ inputs
)
children.push(child)
return child
@@ -259,6 +289,8 @@ export const piScriptedChild = (options: { signedOut?: boolean } = {}): Scripted
resumes: () => resumed,
closes: () => closed,
wire: () => wire,
+ inputs: () => inputs,
+ setNativeEffort: (level) => children.at(-1)?.setNativeEffort(level),
signIn: () => {
signedOut = false
}
diff --git a/src/main/pi/rpc-model-catalog-probe.test.ts b/src/main/pi/rpc-model-catalog-probe.test.ts
index e42d4534e1d..d692e93c628 100644
--- a/src/main/pi/rpc-model-catalog-probe.test.ts
+++ b/src/main/pi/rpc-model-catalog-probe.test.ts
@@ -1,32 +1,28 @@
import { describe, expect, it, vi } from 'vitest'
-import { createPiModelCatalogProbe, piModelCatalogFromListing } from './rpc-model-catalog-probe'
+import type { ProviderProcessLaunch } from '../provider-process/provider-process-launch'
+import { createPiModelCatalogProbe } from './rpc-model-catalog-probe'
+import { readPiRpcSessionOptions } from './rpc-options'
-const TABLE = [
- 'provider model context max-out thinking images',
- 'anthropic claude-sonnet-4 200K 64K yes yes',
- 'openai gpt-4o-mini 128K 16K no yes'
-].join('\n')
+const AVAILABLE_MODELS = {
+ models: [
+ {
+ provider: 'openai',
+ id: 'gpt-6',
+ name: 'GPT-6',
+ reasoning: true,
+ thinkingLevelMap: { off: null, xhigh: 'xhigh' }
+ },
+ { provider: 'openai', id: 'gpt-4o-mini', name: 'GPT-4o mini', reasoning: false }
+ ]
+}
describe('Pi model catalog', () => {
- it('reuses the listing identity, with the levels every reasoning model keeps and no default', () => {
- expect(piModelCatalogFromListing(TABLE)).toEqual([
- {
- id: 'anthropic/claude-sonnet-4',
- label: expect.any(String),
- isDefault: false,
- efforts: ['off', 'minimal', 'low', 'medium', 'high'].map((level) => ({
- value: level,
- label: level
- }))
- },
- { id: 'openai/gpt-4o-mini', label: expect.any(String), isDefault: false, efforts: [] }
- ])
- })
-
it.each(['', `"${process.execPath}" run -- pi`])(
- 'lists under the pinned account with the chat launch env, through the shared runner for Command %j',
+ 'lists the native menu through sessionless RPC for Command %j',
async (command) => {
- const runListing = vi.fn(async () => TABLE)
+ const launches: ProviderProcessLaunch[] = []
+ const close = vi.fn(async () => undefined)
+ const probeVersion = vi.fn(async () => ({ version: '0.84.0' }))
const probe = createPiModelCatalogProbe({
resolveEnvironment: async () => ({
PATH: '/usr/bin',
@@ -35,34 +31,125 @@ describe('Pi model catalog', () => {
}),
resolveCommandSettings: () => ({ agentCmdOverrides: { pi: command } }),
resolveCommand: () => '/opt/pi/bin/pi',
- probeVersion: async () => ({ version: '0.84.0' }),
+ probeVersion,
homePath: '/home/user',
- runListing
+ connect: (launch) => {
+ launches.push(launch)
+ return {
+ request: async (command) => {
+ expect(command).toBe('get_available_models')
+ return AVAILABLE_MODELS
+ },
+ close
+ }
+ }
})
const success = await probe({ variable: 'PI_CODING_AGENT_DIR', path: '/homes/pi-a' })
- expect(success.models).toHaveLength(2)
- expect(runListing).toHaveBeenCalledWith(
+ const levels = (values: string[]) => values.map((value) => ({ value, label: value }))
+ expect(success.models).toEqual([
+ {
+ id: 'openai/gpt-6',
+ label: 'GPT-6',
+ isDefault: false,
+ efforts: levels(['minimal', 'low', 'medium', 'high', 'xhigh'])
+ },
+ { id: 'openai/gpt-4o-mini', label: 'GPT-4o mini', isDefault: false, efforts: [] }
+ ])
+ const live = await readPiRpcSessionOptions({
+ request: async (command) =>
+ command === 'get_available_models'
+ ? AVAILABLE_MODELS
+ : { sessionFile: '/s.jsonl', isStreaming: false, isCompacting: false }
+ })
+ expect(success.models).toEqual(live.models)
+ expect(launches).toEqual([
expect.objectContaining({
command: command ? process.execPath : '/opt/pi/bin/pi',
- args: [...(command ? ['run', '--', 'pi'] : []), '--list-models'],
- env: expect.objectContaining({ PI_CODING_AGENT_DIR: '/homes/pi-a' })
- }),
- { site: 'pi-model-catalog-probe' }
+ cwd: '/home/user',
+ args: [...(command ? ['run', '--', 'pi'] : []), '--mode', 'rpc', '--no-session'],
+ env: expect.objectContaining({ PI_CODING_AGENT_DIR: '/homes/pi-a' }),
+ // Orca's status extension stays silent in a probe that belongs to no pane.
+ envToDelete: expect.arrayContaining(['ORCA_PANE_KEY'])
+ })
+ ])
+ expect(probeVersion).toHaveBeenCalledWith(
+ expect.objectContaining({
+ program: command ? process.execPath : '/opt/pi/bin/pi',
+ prefixArgs: command ? ['run', '--', 'pi'] : []
+ })
)
+ expect(close).toHaveBeenCalledOnce()
}
)
- it('lists nothing from a Pi that runs no structured chat', async () => {
+ it('falls back to the text listing when Pi cannot answer over RPC', async () => {
+ const runListing = vi.fn(async () =>
+ [
+ 'provider model context max-out thinking images',
+ 'anthropic claude-sonnet-4 200K 64K yes yes',
+ 'openai gpt-4o-mini 128K 16K no yes'
+ ].join('\n')
+ )
+ const probe = createPiModelCatalogProbe({
+ resolveEnvironment: async () => ({ PATH: '/usr/bin' }),
+ resolveCommandSettings: () => ({
+ agentCmdOverrides: { pi: `"${process.execPath}" run -- pi` }
+ }),
+ resolveCommand: () => '/opt/pi/bin/pi',
+ probeVersion: async () => ({ version: '0.84.0' }),
+ homePath: '/home/user',
+ connect: () => ({
+ request: async () => {
+ throw new Error('pi exited before answering')
+ },
+ close: async () => undefined
+ }),
+ runListing
+ })
+ const success = await probe({ variable: 'PI_CODING_AGENT_DIR', path: '/homes/pi-a' })
+ expect(success.models.map((model) => [model.id, model.efforts.length])).toEqual([
+ ['anthropic/claude-sonnet-4', 5],
+ ['openai/gpt-4o-mini', 0]
+ ])
+ expect(runListing).toHaveBeenCalledWith(
+ expect.objectContaining({ args: ['run', '--', 'pi', '--list-models'] }),
+ expect.objectContaining({ site: 'pi-model-catalog-probe' })
+ )
+ })
+
+ it('does not fall back when stopped during RPC teardown', async () => {
+ const stop = new AbortController()
const runListing = vi.fn()
const probe = createPiModelCatalogProbe({
resolveEnvironment: async () => ({ PATH: '/usr/bin' }),
resolveCommand: () => '/opt/pi/bin/pi',
- probeVersion: async () => ({ version: '0.83.9' }),
+ probeVersion: async () => ({ version: '1.1.0' }),
+ homePath: '/home/user',
+ connect: () => ({
+ request: async () => {
+ throw new Error('RPC interrupted')
+ },
+ close: async () => stop.abort()
+ }),
runListing
})
+ await expect(
+ probe({ variable: 'PI_CODING_AGENT_DIR', path: '/homes/pi' }, { signal: stop.signal })
+ ).rejects.toThrow()
+ expect(runListing).not.toHaveBeenCalled()
+ })
+
+ it('lists nothing from a Pi that runs no structured chat', async () => {
+ const connect = vi.fn()
+ const probe = createPiModelCatalogProbe({
+ resolveEnvironment: async () => ({ PATH: '/usr/bin' }),
+ resolveCommand: () => '/opt/pi/bin/pi',
+ probeVersion: async () => ({ version: '0.83.9' }),
+ connect
+ })
await expect(probe({ variable: 'PI_CODING_AGENT_DIR', path: '/homes/pi-a' })).rejects.toThrow(
/does not run structured chats/
)
- expect(runListing).not.toHaveBeenCalled()
+ expect(connect).not.toHaveBeenCalled()
})
})
diff --git a/src/main/pi/rpc-model-catalog-probe.ts b/src/main/pi/rpc-model-catalog-probe.ts
index 2c825cde867..53ddd3a6722 100644
--- a/src/main/pi/rpc-model-catalog-probe.ts
+++ b/src/main/pi/rpc-model-catalog-probe.ts
@@ -4,15 +4,22 @@ import { requireLegacyAgentSessionAccountHome } from '../../shared/agent-session
import { parsePiModels } from '../../shared/commit-message-model-parsers'
import type { resolveCliCommand } from '../../shared/node-cli-command-resolution'
import type { AgentCliVersionReader } from '../agent-cli-version-probe'
+import { JsonlRpcAgentConnection } from '../jsonl-rpc/agent-connection'
import type {
AgentModelCatalogProbe,
AgentModelCatalogSuccess
} from '../native-chat/agent-model-catalog/agent-model-catalog-store'
-import { runAgentModelCatalogListing } from '../native-chat/agent-model-catalog/agent-model-catalog-probe-runner'
+import {
+ runAgentModelCatalogListing,
+ runAgentModelCatalogSession
+} from '../native-chat/agent-model-catalog/agent-model-catalog-probe-runner'
import type { StructuredAgentCommandSettings } from '../native-chat/structured-agent-command-resolution'
+import type { ProviderProcessLaunch } from '../provider-process/provider-process-launch'
import { buildPiRpcLaunch, piRpcSessionlessEnvironment } from './rpc-launch'
import { checkPiRpcVersion, resolvePiRpcInvocation } from './rpc-launch-resolution'
-import { PI_UNMAPPED_THINKING_LEVELS } from './rpc-options'
+import { readPiRpcModelOptions, type PiRpcRequester } from './rpc-options'
+
+type PiModelCatalogConnection = PiRpcRequester & { close(): Promise<unknown> }
export type PiModelCatalogProbeDeps = {
resolveEnvironment: () => Promise<NodeJS.ProcessEnv>
@@ -21,22 +28,40 @@ export type PiModelCatalogProbeDeps = {
resolveCommandSettings?: () => StructuredAgentCommandSettings
resolveCommand?: typeof resolveCliCommand
probeVersion?: AgentCliVersionReader
+ connect?: (launch: ProviderProcessLaunch) => PiModelCatalogConnection
runListing?: typeof runAgentModelCatalogListing
homePath?: string
}
-/** Listings omit default/model-specific thinking choices; expose only levels common to reasoning maps. */
+/** The text listing has no per-model thinking map; offer the levels every reasoning model keeps. */
export function piModelCatalogFromListing(stdout: string): AgentModelCatalogSuccess['models'] {
return parsePiModels(stdout).map((model) => ({
id: model.id,
label: model.label,
isDefault: false,
efforts: model.thinkingLevels
- ? PI_UNMAPPED_THINKING_LEVELS.map((level) => ({ value: level, label: level }))
+ ? ['off', 'minimal', 'low', 'medium', 'high'].map((level) => ({ value: level, label: level }))
: []
}))
}
+function connectPiModelCatalog(launch: ProviderProcessLaunch): PiModelCatalogConnection {
+ const connection: JsonlRpcAgentConnection = new JsonlRpcAgentConnection(launch, {
+ // Nobody can answer an extension's dialog during discovery; cancelling lets Pi continue.
+ onRecord: (frame) => {
+ if (
+ frame.type === 'extension_ui_request' &&
+ (typeof frame.id === 'string' || typeof frame.id === 'number')
+ ) {
+ void connection
+ .send({ type: 'extension_ui_response', id: frame.id, cancelled: true })
+ .catch(() => undefined)
+ }
+ }
+ })
+ return connection
+}
+
export function createPiModelCatalogProbe(deps: PiModelCatalogProbeDeps): AgentModelCatalogProbe {
return async (accountHome, options): Promise<AgentModelCatalogSuccess> => {
const operation = options?.operation ?? { signal: options?.signal }
@@ -59,15 +84,33 @@ export function createPiModelCatalogProbe(deps: PiModelCatalogProbeDeps): AgentM
}
const launch = buildPiRpcLaunch({
command,
+ prefixArgs,
cwd,
...piRpcSessionlessEnvironment(env),
fullAccess: true
})
- const stdout = await (deps.runListing ?? runAgentModelCatalogListing)(
- { ...launch, args: [...prefixArgs, '--list-models'] },
- { site: 'pi-model-catalog-probe', signal: options?.signal }
- )
- const models = piModelCatalogFromListing(stdout)
+ let models: AgentModelCatalogSuccess['models']
+ try {
+ models = await runAgentModelCatalogSession(
+ () =>
+ (deps.connect ?? connectPiModelCatalog)({
+ ...launch,
+ args: [...launch.args, '--no-session']
+ }),
+ readPiRpcModelOptions,
+ { label: 'pi', signal: options?.signal }
+ )
+ } catch (error) {
+ if (options?.signal?.aborted) {
+ throw error
+ }
+ // Pi reads RPC input only after extensions start, so a startup dialog can block it; the listing exits first.
+ const stdout = await (deps.runListing ?? runAgentModelCatalogListing)(
+ { ...launch, args: [...prefixArgs, '--list-models'] },
+ { site: 'pi-model-catalog-probe', signal: options?.signal }
+ )
+ models = piModelCatalogFromListing(stdout)
+ }
if (models.length === 0) {
throw new Error('pi listed no models')
}
diff --git a/src/main/pi/rpc-options.ts b/src/main/pi/rpc-options.ts
index 8d97f2ae2dd..28740227af6 100644
--- a/src/main/pi/rpc-options.ts
+++ b/src/main/pi/rpc-options.ts
@@ -1,4 +1,6 @@
+import { withLiveCatalogListing } from '../native-chat/agent-model-catalog/agent-model-catalog-entry'
import { z } from 'zod'
+import { PI_THINKING_LEVELS } from '../../shared/structured-agent-session-effective-effort'
import { waitForPromiseWithSignal } from '../../shared/abort-signal-reason'
import type {
AgentSessionCommandsResult,
@@ -33,12 +35,6 @@ const commandsSchema = z.object({
)
})
-const THINKING_LEVELS = ['off', 'minimal', 'low', 'medium', 'high', 'xhigh', 'max'] as const
-/** The levels a reasoning model offers unless its thinking map removes one; the rest need a map entry. */
-export const PI_UNMAPPED_THINKING_LEVELS = THINKING_LEVELS.filter(
- (level) => level !== 'xhigh' && level !== 'max'
-)
-
export function piModelOptionId(provider: string, modelId: string): string {
if (!provider || !modelId || provider.includes('/')) {
throw new Error('Pi model requires an explicit provider and model ID')
@@ -54,19 +50,17 @@ export function parsePiModelOptionId(value: string): { provider: string; modelId
return { provider: value.slice(0, slash), modelId: value.slice(slash + 1) }
}
-export async function readPiRpcSessionOptions(
- rpc: PiRpcRequester,
- beforeStateRead?: () => void
-): Promise<AgentSessionOptionsResult> {
+/** Native inventory projection shared by running chats and the pre-session catalog. */
+export async function readPiRpcModelOptions(
+ rpc: PiRpcRequester
+): Promise<AgentSessionOptionsResult['models']> {
const models = modelsSchema.parse(await rpc.request('get_available_models')).models
- beforeStateRead?.()
- const state = stateSchema.parse(await rpc.request('get_state'))
- const listed = models.map((model) => {
+ return models.map((model) => {
const id = piModelOptionId(model.provider, model.id)
const efforts =
model.reasoning !== true
? []
- : THINKING_LEVELS.filter((level) => {
+ : PI_THINKING_LEVELS.filter((level) => {
const mapped = model.thinkingLevelMap?.[level]
return (
mapped !== null && ((level !== 'xhigh' && level !== 'max') || mapped !== undefined)
@@ -79,6 +73,15 @@ export async function readPiRpcSessionOptions(
efforts
}
})
+}
+
+export async function readPiRpcSessionOptions(
+ rpc: PiRpcRequester,
+ beforeStateRead?: () => void
+): Promise<AgentSessionOptionsResult> {
+ const listed = await readPiRpcModelOptions(rpc)
+ beforeStateRead?.()
+ const state = stateSchema.parse(await rpc.request('get_state'))
return {
models: listed,
current: piRpcStateOptions(state)
@@ -107,6 +110,7 @@ export type PiRpcOptionProof = {
export class PiRpcOptionObservations {
private observed: AgentSessionOptionsResult = { models: [], current: {} }
private writes = new Map<string, PiRpcOptionWrite>()
+ private consumed = new Map<string, string>()
constructor(
private readonly proof: PiRpcOptionProof,
private readonly current: () => boolean
@@ -118,6 +122,7 @@ export class PiRpcOptionObservations {
prepare(): (options: AgentSessionOptionsResult) => boolean {
const writes = new Map(this.proof.writes)
+ const consumed = new Map(this.proof.current)
return (options) => {
if (!this.current()) {
return false
@@ -130,6 +135,7 @@ export class PiRpcOptionObservations {
}
this.observed = options
this.writes = writes
+ this.consumed = consumed
return true
}
}
@@ -144,7 +150,7 @@ export class PiRpcOptionObservations {
}
}
- read(): AgentSessionOptionsResult {
+ read() {
const current = { ...this.observed.current }
const confirmed = new Set(current.confirmed)
for (const key of ['model', 'effort'] as const) {
@@ -156,7 +162,40 @@ export class PiRpcOptionObservations {
confirmed.delete(key)
}
}
- return { ...this.observed, current: { ...current, confirmed: [...confirmed] } }
+ const answer = { ...this.observed, current: { ...current, confirmed: [...confirmed] } }
+ const writes = this.writes
+ const consumed = this.consumed
+ return {
+ ...withLiveCatalogListing(answer),
+ projectCurrent: (saved: Readonly<Record<string, string>>) => {
+ const model = saved.model ?? answer.current.model
+ const unchanged =
+ this.current() &&
+ ['model', 'effort'].every(
+ (key) =>
+ !this.proof.writes.get(key)?.pending &&
+ this.proof.writes.get(key) === writes.get(key) &&
+ this.proof.current.get(key) === consumed.get(key)
+ )
+ const sameApplication =
+ unchanged &&
+ model === answer.current.model &&
+ model === consumed.get('model') &&
+ saved.effort === consumed.get('effort')
+ const useActual =
+ unchanged &&
+ model === answer.current.model &&
+ (saved.effort === undefined || sameApplication)
+ return {
+ ...answer.current,
+ // Unapplied intent stays raw in transport so later catalogs can rederive the display.
+ effort: useActual ? answer.current.effort : (saved.effort ?? answer.current.effort),
+ confirmed: answer.current.confirmed.filter(
+ (key) => unchanged && (key !== 'effort' || useActual)
+ )
+ }
+ }
+ }
}
}
@@ -176,7 +215,7 @@ export async function applyPiRpcSessionOption(
command = 'set_model'
params = model
} else if (key === 'effort') {
- if (!THINKING_LEVELS.some((level) => level === value)) {
+ if (!PI_THINKING_LEVELS.some((level) => level === value)) {
throw new Error(`Unsupported Pi thinking level: ${value}`)
}
command = 'set_thinking_level'
diff --git a/src/main/pi/rpc-runtime-metadata.ts b/src/main/pi/rpc-runtime-metadata.ts
index 4bc7cae76d6..aa5bdd1a346 100644
--- a/src/main/pi/rpc-runtime-metadata.ts
+++ b/src/main/pi/rpc-runtime-metadata.ts
@@ -13,7 +13,7 @@ export const PI_RPC_RUNTIME_METADATA: StructuredAgentRuntimeMetadata = {
definition: PI_RPC_AGENT,
modelCatalog: (context) => ({
kind: 'probe',
- // `--list-models` marks no model as the one Pi runs by default.
+ // `get_available_models` marks no model as the one Pi runs by default.
listingNamesConfiguredModel: false,
probe: createPiModelCatalogProbe({
resolveEnvironment: () => context.environment.resolveAgentEnvironment('pi'),
diff --git a/src/main/pi/rpc-session-adapter.test.ts b/src/main/pi/rpc-session-adapter.test.ts
index 913516b51da..753d22c0d18 100644
--- a/src/main/pi/rpc-session-adapter.test.ts
+++ b/src/main/pi/rpc-session-adapter.test.ts
@@ -18,6 +18,124 @@ import { agentSessionLaunchFolderMissing } from '../runtime/agent-session-launch
afterEach(closePiRpcAdapterFixtures)
describe('Pi RPC session ownership and delivery', () => {
+ it('keeps passive, request-scoped actual separate from future picks and raw successful controls', async () => {
+ const h = await setup({}, undefined, { thinkingLevel: 'medium' })
+ await vi.waitFor(() => expect(h.connection.requests).toContain('get_commands'))
+ const model = { provider: 'anthropic', id: 'model-1', reasoning: true }
+ let effort: string | undefined = 'minimal'
+ h.connection.requestOverride = (command) => {
+ if (command === 'set_thinking_level') {
+ return Promise.resolve({}) // Native success has no echo.
+ }
+ if (command === 'get_state') {
+ return Promise.resolve({
+ sessionFile: file,
+ model,
+ thinkingLevel: effort,
+ isStreaming: false,
+ isCompacting: false
+ })
+ }
+ return undefined
+ }
+ const pick = (key: string, value: string) =>
+ h.adapter.setOption({ sessionId, fence: 7, key, value })
+ const read = () => h.adapter.readOptions({ sessionId, fence: 7 })
+ const saved = { model: 'anthropic/model-1', effort: 'off' }
+ const settle = async () => {
+ const reports = h.lifecycle.mock.calls.length
+ h.connection.receive({ type: 'agent_start' })
+ h.connection.receive({ type: 'agent_settled' })
+ await vi.waitFor(() => expect(h.lifecycle.mock.calls.length).toBeGreaterThan(reports))
+ }
+ await pick('model', saved.model)
+ await pick('effort', saved.effort)
+ expect((await read()).projectCurrent?.(saved)).toMatchObject({ effort: 'off', confirmed: [] })
+ await settle()
+ const applied = await read()
+ expect(applied.projectCurrent?.(saved)).toMatchObject({
+ effort: 'minimal',
+ confirmed: expect.arrayContaining(['effort'])
+ })
+ const requests = h.connection.requests.length
+ await read()
+ await read()
+ expect(h.connection.requests).toHaveLength(requests)
+ expect(applied.projectCurrent?.({ ...saved, effort: 'high' })).toMatchObject({
+ effort: 'high',
+ confirmed: ['model']
+ })
+
+ // An extension changes actual; equal raw input skips setters and leaves that actual intact.
+ effort = 'low'
+ await settle()
+ const changed = await read()
+ expect(changed.projectCurrent?.(saved)).toMatchObject({
+ effort: 'low',
+ confirmed: ['model', 'effort']
+ })
+ const controls = h.connection.requests.filter((command) => command.startsWith('set_'))
+ expect(
+ await h.adapter.dispatch({
+ sessionId,
+ fence: 7,
+ clientMessageId: 'equal-raw',
+ executionOptions: saved,
+ body: { kind: 'message', role: 'user', blocks: [{ type: 'text', text: 'same request' }] }
+ })
+ ).toMatchObject({ state: 'admitted', ranOptions: saved })
+ expect(h.connection.requests.filter((command) => command.startsWith('set_'))).toEqual(controls)
+
+ const pending = Promise.withResolvers<unknown>()
+ const requested = Promise.withResolvers<void>()
+ const ordinary = h.connection.requestOverride
+ h.connection.requestOverride = (command) => {
+ if (command === 'get_state') {
+ requested.resolve()
+ return pending.promise
+ }
+ return ordinary(command)
+ }
+ h.connection.receive({ type: 'agent_start' })
+ h.connection.receive({ type: 'agent_settled' })
+ await requested.promise
+ await pick('effort', 'high')
+ pending.resolve({
+ sessionFile: file,
+ model,
+ thinkingLevel: 'minimal',
+ isStreaming: false,
+ isCompacting: false
+ })
+ await vi.waitFor(async () => expect((await read()).current.effort).toBe('high'))
+ expect((await read()).projectCurrent?.({ ...saved, effort: 'high' })).toMatchObject({
+ effort: 'high',
+ confirmed: []
+ })
+ expect(applied.projectCurrent?.(saved)?.confirmed).toEqual([])
+
+ h.connection.requestOverride = ordinary
+ effort = undefined
+ await settle()
+ expect((await read()).projectCurrent?.({ ...saved, effort: 'high' })?.confirmed).not.toContain(
+ 'effort'
+ )
+ h.connection.requestOverride = (command) =>
+ command === 'set_thinking_level'
+ ? Promise.reject(new Error('native refused'))
+ : ordinary(command)
+ await expect(pick('effort', 'low')).rejects.toThrow('native refused')
+ expect((await read()).projectCurrent?.({ ...saved, effort: 'high' })?.confirmed).not.toContain(
+ 'effort'
+ )
+ await pick('model', 'anthropic/workspace-model')
+ expect(
+ (await read()).projectCurrent?.({ model: 'anthropic/workspace-model', effort: 'off' })
+ ).toMatchObject({ effort: 'off', confirmed: [] })
+ await h.adapter.closeSession(sessionId)
+ expect(changed.projectCurrent?.(saved)?.confirmed).toEqual([])
+ })
+
it('refuses a floating chat whose folder is gone with the reason the person reads', async () => {
const h = await setup()
await h.adapter.closeSession(sessionId)
@@ -218,7 +336,10 @@ describe('Pi RPC session ownership and delivery', () => {
state: 'admitted',
ranOptions: { model: 'anthropic/model-2', effort: 'low' }
})
- expect(h.connection.requests.slice(-2)).toEqual(['set_model', 'set_thinking_level'])
+ expect(h.connection.requests.filter((command) => command.startsWith('set_'))).toEqual([
+ 'set_model',
+ 'set_thinking_level'
+ ])
expect(h.connection.sent).toMatchObject([{ type: 'prompt', message: 'chosen' }])
})
diff --git a/src/main/runtime/structured-agent-session-pi-startup.test.ts b/src/main/runtime/structured-agent-session-pi-startup.test.ts
index a0b532f55ea..5253c980206 100644
--- a/src/main/runtime/structured-agent-session-pi-startup.test.ts
+++ b/src/main/runtime/structured-agent-session-pi-startup.test.ts
@@ -6,9 +6,25 @@ import { computeAgentSessionPayloadFingerprint } from '../../shared/agent-sessio
import {
hostTestAttachParams,
hostTestMessage,
+ HOST_TEST_NOW,
HOST_TEST_SESSION
} from '../native-chat/agent-session-wire/structured-agent-session-host-test-data'
import { createStructuredAgentSessionLogger } from '../native-chat/agent-session-wire/structured-agent-session-logger'
+import { structuredAgentSessionResumeParams } from '../native-chat/agent-session-wire/structured-agent-session-resume-eligibility'
+import type { OrcaRuntimeService } from './orca-runtime'
+import { prepareStructuredAgentSessionCreateForWorktree } from './rpc/methods/structured-agent-session-create'
+import type { AgentSessionModelOption } from '../../shared/agent-session-wire'
+import { structuredAgentSessionSeedCatalog } from '../../shared/structured-agent-session-seed-catalog'
+import {
+ applyStructuredAgentSessionModelCatalog,
+ applyStructuredAgentSessionOptions,
+ createStructuredAgentSessionOptionState
+} from '../../shared/structured-agent-session-options'
+import {
+ structuredAgentSessionShownSnapshot,
+ structuredAgentSessionMessageSelection
+} from '../../shared/structured-agent-session-option-view'
+import { readPiRpcModelOptions } from '../pi/rpc-options'
import { piScriptedChild } from '../pi/pi-scripted-child.test-fixture'
import { peekOpenedAgentSessionRecordStore } from './agent-session-record-store-slot'
import {
@@ -23,15 +39,24 @@ const operationId = () => `${Date.now()}-${(++operations).toString(16).padStart(
afterEach(async () => {
await stopStructuredAgentSessionRuntime()
if (directory) {
- await rm(directory, { recursive: true, force: true })
+ await rm(directory, { recursive: true, force: true, maxRetries: 3 })
directory = undefined
}
})
-async function setup() {
+async function setup(
+ options: {
+ native?: Parameters<typeof piScriptedChild>[0]
+ seed?: Record<string, string>
+ explicit?: Record<string, string>
+ catalog?: AgentSessionModelOption[]
+ create?: true
+ firstMessage?: string
+ } = {}
+) {
directory = await mkdtemp(join(tmpdir(), 'orca-pi-startup-'))
const root = directory
- const script = piScriptedChild()
+ const script = piScriptedChild(options.native)
const host = await ensureStructuredAgentSessionHost({
logger: createStructuredAgentSessionLogger(),
stateDirectory: root,
@@ -41,10 +66,26 @@ async function setup() {
resolveClaudeAuthPolicy: () => ({ account: 'managed' }),
resolveLaunchArgs: () => [],
resolveEnvironment: async () => ({}),
+ ...(options.catalog
+ ? {
+ resolveAgentAccountHome: async () => ({
+ variable: 'PI_CODING_AGENT_DIR' as const,
+ path: root
+ })
+ }
+ : {}),
...script.deps
})
+ if (options.catalog) {
+ vi.spyOn(host.deps.modelCatalog!, 'read').mockResolvedValue({
+ origin: 'probe',
+ fetchedAt: 1,
+ models: options.catalog
+ })
+ }
const caller = { callerKey: 'pi-startup-test' }
const params = hostTestAttachParams(null, {
+ ...(options.seed ? { options: options.seed } : {}),
provider: 'pi',
agent: 'pi',
providerHandle: undefined,
@@ -57,12 +98,45 @@ async function setup() {
}
})
params.envelope.clientOperationId = operationId()
- const attached = await host.attach(caller, params)
+ let preparedParams = params
+ let catalogModels: readonly AgentSessionModelOption[] | undefined
+ if (options.create) {
+ // oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: preparation reaches only these runtime resolvers; host/capture/adapter are real.
+ const runtime = {
+ resolveStructuredAgentSessionCreateIntent: async () => params,
+ resolveStructuredAgentSessionLocalWorkspacePath: async () => root
+ } as unknown as OrcaRuntimeService
+ const prepared = await prepareStructuredAgentSessionCreateForWorktree({
+ runtime,
+ ensureHost: async () => host,
+ envelope: params.envelope,
+ worktree: 'id:folder-1',
+ agent: 'pi',
+ caller,
+ options: options.explicit,
+ atRest: true
+ })
+ preparedParams = prepared.attachParams
+ catalogModels = prepared.catalogModels
+ }
+ const attached = options.create
+ ? await host.create(caller, preparedParams, {
+ catalogModels,
+ ...(options.firstMessage
+ ? {
+ firstMessage: {
+ clientMessageId: operationId(),
+ body: hostTestMessage(options.firstMessage)
+ }
+ }
+ : {})
+ })
+ : await host.attach(caller, params)
expect(attached.ok).toBe(true)
if (!attached.ok) {
throw new Error(JSON.stringify(attached.refusal))
}
- return { script, host, caller, fence: attached.value.fence }
+ return { script, host, caller, params: preparedParams, fence: attached.value.fence }
}
function envelope(method: string, fields: Record<string, unknown>) {
@@ -138,6 +212,11 @@ it('writes startup model and effort picks before a message accepted after them',
expect(wire.indexOf('set_model')).toBeGreaterThanOrEqual(0)
expect(wire.indexOf('set_thinking_level')).toBeGreaterThan(wire.indexOf('set_model'))
expect(wire.indexOf('prompt:first message')).toBeGreaterThan(wire.indexOf('set_thinking_level'))
+ expect(stateInputs(script)).toMatchObject([
+ { command: 'set_model', params: { provider: 'scripted', modelId: 'model-2' } },
+ { command: 'set_thinking_level', params: { level: 'low' } },
+ { command: 'prompt', params: { message: 'first message', effort: 'low' } }
+ ])
expect(peekOpenedAgentSessionRecordStore()?.getRecord(HOST_TEST_SESSION)?.options).toMatchObject({
model: 'scripted/model-2',
effort: 'low'
@@ -179,3 +258,290 @@ it('ends Pi on Stop and resumes its real session file when the next send starts
expect(script.prompts()).toEqual(['start a long turn', 'resume after Stop'])
)
})
+
+const gpt5 = {
+ provider: 'openai-codex',
+ id: 'gpt-6.1-sol',
+ reasoning: true,
+ thinkingLevelMap: {
+ off: null,
+ minimal: 'low',
+ low: 'low',
+ medium: 'medium',
+ high: 'high',
+ xhigh: 'xhigh',
+ max: 'max'
+ }
+}
+const stateInputs = (script: ReturnType<typeof piScriptedChild>) =>
+ script.inputs().filter(({ command }) => command.startsWith('set_') || command === 'prompt')
+const sendText = (
+ host: Awaited<ReturnType<typeof setup>>['host'],
+ caller: { callerKey: string },
+ text: string,
+ selection?: Readonly<Record<string, string>>
+) => {
+ const body = hostTestMessage(text)
+ const fields = { body, ...(selection !== undefined ? { selection } : {}) }
+ return host.send(caller, { envelope: envelope('agentSession.send', fields), ...fields })
+}
+
+function displayed(
+ answer: Awaited<ReturnType<Awaited<ReturnType<typeof setup>>['host']['readOptions']>>
+) {
+ const seed = structuredAgentSessionSeedCatalog('pi')
+ return structuredAgentSessionShownSnapshot(
+ applyStructuredAgentSessionOptions(
+ createStructuredAgentSessionOptionState('pi', seed),
+ seed,
+ answer
+ )
+ ).find((entry) => entry.id === 'effort')
+}
+
+it('keeps remembered and explicit raw off through create while native application is minimal', async () => {
+ const models = await readPiRpcModelOptions({ request: async () => ({ models: [gpt5] }) })
+ const h = await setup({
+ create: true,
+ seed: { model: 'openai-codex/gpt-6.1-sol', effort: 'off' },
+ catalog: models,
+ native: { model: gpt5, appliedEfforts: { off: 'minimal' } },
+ firstMessage: 'new seed'
+ })
+ expect(h.params.options).toEqual({ model: 'openai-codex/gpt-6.1-sol', effort: 'off' })
+ expect(displayed(await h.host.readOptions(HOST_TEST_SESSION))).toMatchObject({
+ kind: { currentValue: 'minimal', choices: models[0]!.efforts }
+ })
+ expect(models[0]!.efforts.map(({ value }) => value)).toEqual([
+ 'minimal',
+ 'low',
+ 'medium',
+ 'high',
+ 'xhigh',
+ 'max'
+ ])
+ await vi.waitFor(() => expect(h.script.spawns()).toBe(1))
+ h.script.releaseHandshake()
+ await vi.waitFor(() => expect(h.script.prompts()).toEqual(['new seed']))
+ expect(stateInputs(h.script)).toMatchObject([
+ { command: 'set_model', params: { provider: 'openai-codex', modelId: 'gpt-6.1-sol' } },
+ { command: 'set_thinking_level', params: { level: 'off' } },
+ { command: 'prompt', params: { message: 'new seed', effort: 'minimal' } }
+ ])
+ const explicit = {
+ ...h.params,
+ options: { model: 'openai-codex/gpt-6.1-sol', effort: 'off' },
+ envelope: { ...h.params.envelope, sessionId: 'explicit-off', clientOperationId: operationId() }
+ }
+ expect(await h.host.create(h.caller, explicit, { catalogModels: models })).toMatchObject({
+ ok: true
+ })
+})
+
+it('restores blank raw intent through start/capture and preserves an accepted high until its next dispatch', async () => {
+ // Home discovery and a workspace extension may disagree; live support owns live projection.
+ const models = await readPiRpcModelOptions({ request: async () => ({ models: [gpt5] }) })
+ const h = await setup({
+ create: true,
+ seed: { model: 'openai-codex/gpt-6.1-sol', effort: 'minimal' },
+ catalog: models,
+ native: { model: gpt5, appliedEfforts: { off: 'minimal' } }
+ })
+ const store = peekOpenedAgentSessionRecordStore()!
+ await store.replaceSessionOptions({
+ sessionId: HOST_TEST_SESSION,
+ fence: h.fence,
+ options: { model: 'openai-codex/gpt-6.1-sol', effort: 'off' },
+ now: HOST_TEST_NOW
+ })
+ const resting = await h.host.readOptions(HOST_TEST_SESSION)
+ expect(resting.current.effort).toBe('off')
+ expect(displayed(resting)).toMatchObject({ kind: { currentValue: 'minimal' } })
+ expect(store.getRecord(HOST_TEST_SESSION)?.options?.effort).toBe('off')
+ const resume = structuredAgentSessionResumeParams(
+ store.getRecord(HOST_TEST_SESSION)!,
+ operationId()
+ )
+ expect(resume).not.toBeNull()
+ const started = await h.host.attach(h.caller, resume!)
+ expect(started).toMatchObject({ ok: true })
+ await vi.waitFor(() => expect(h.script.spawns()).toBe(1))
+ h.script.releaseHandshake()
+ await vi.waitFor(() => expect(h.script.wire()).toContain('get_commands'))
+ expect((await sendText(h.host, h.caller, 'restored blank')).ok).toBe(true)
+ await vi.waitFor(() => expect(h.script.prompts()).toEqual(['restored blank']))
+ expect(stateInputs(h.script)).toMatchObject([
+ { command: 'set_model', params: { provider: 'openai-codex', modelId: 'gpt-6.1-sol' } },
+ { command: 'set_thinking_level', params: { level: 'off' } },
+ { command: 'prompt', params: { message: 'restored blank', effort: 'minimal' } }
+ ])
+ vi.mocked(h.host.deps.modelCatalog!.read).mockResolvedValue({
+ origin: 'probe',
+ fetchedAt: 2,
+ models: [{ ...models[0]!, efforts: [{ value: 'off', label: 'Off' }] }]
+ })
+ await vi.waitFor(async () =>
+ expect((await h.host.readOptions(HOST_TEST_SESSION)).current).toMatchObject({
+ effort: 'off',
+ reportedEffort: 'minimal'
+ })
+ )
+ const capture = (answer: Awaited<ReturnType<typeof h.host.readOptions>>) => {
+ const seed = structuredAgentSessionSeedCatalog('pi')
+ return structuredAgentSessionMessageSelection(
+ applyStructuredAgentSessionOptions(
+ createStructuredAgentSessionOptionState('pi', seed),
+ seed,
+ answer
+ )
+ )
+ }
+ h.script.setNativeEffort('low')
+ expect(
+ (
+ await sendText(
+ h.host,
+ h.caller,
+ 'same raw off',
+ capture(await h.host.readOptions(HOST_TEST_SESSION))
+ )
+ ).ok
+ ).toBe(true)
+ await vi.waitFor(async () =>
+ expect((await h.host.readOptions(HOST_TEST_SESSION)).current).toMatchObject({
+ effort: 'off',
+ reportedEffort: 'low'
+ })
+ )
+ expect(stateInputs(h.script).at(-1)).toMatchObject({
+ command: 'prompt',
+ params: { effort: 'low' }
+ })
+ expect(
+ stateInputs(h.script).filter(({ command }) => command === 'set_thinking_level')
+ ).toHaveLength(1)
+ const actual = await h.host.readOptions(HOST_TEST_SESSION)
+ const seed = structuredAgentSessionSeedCatalog('pi')
+ const actualState = applyStructuredAgentSessionOptions(
+ createStructuredAgentSessionOptionState('pi', seed),
+ seed,
+ actual
+ )
+ const exact = structuredAgentSessionMessageSelection(actualState)
+ expect(exact.effort).toBe('off')
+ expect((await sendText(h.host, h.caller, 'captured extension', exact)).ok).toBe(true)
+ await vi.waitFor(() => expect(h.script.prompts()).toHaveLength(3))
+ expect(stateInputs(h.script).at(-1)).toMatchObject({
+ command: 'prompt',
+ params: { effort: 'low' }
+ })
+ expect(
+ stateInputs(h.script).filter(({ command }) => command === 'set_thinking_level')
+ ).toHaveLength(1)
+ const late = applyStructuredAgentSessionModelCatalog(
+ actualState,
+ seed,
+ {
+ origin: 'probe',
+ fetchedAt: 3,
+ models: [{ ...models[0]!, efforts: [{ value: 'minimal', label: 'Minimal' }] }]
+ },
+ { newLaunch: false, coherentCatalog: true }
+ )
+ expect(
+ structuredAgentSessionShownSnapshot(late).find((entry) => entry.id === 'effort')
+ ).toMatchObject({ kind: { currentValue: 'low' } })
+ expect(store.getRecord(HOST_TEST_SESSION)?.options?.effort).toBe('off')
+ expect(
+ (
+ await h.host.setOption(h.caller, {
+ envelope: envelope('agentSession.setOption', { key: 'effort', value: 'high' }),
+ key: 'effort',
+ value: 'high'
+ })
+ ).ok
+ ).toBe(true)
+ const future = await h.host.readOptions(HOST_TEST_SESSION)
+ expect(future.current.effort).toBe('high')
+ expect(displayed(future)).toMatchObject({ kind: { currentValue: 'high' } })
+ expect(future.current.confirmed).not.toContain('effort')
+ expect((await sendText(h.host, h.caller, 'accepted high')).ok).toBe(true)
+ await vi.waitFor(() => expect(h.script.prompts()).toHaveLength(4))
+ expect(stateInputs(h.script).slice(-2)).toMatchObject([
+ { command: 'set_thinking_level', params: { level: 'high' } },
+ { command: 'prompt', params: { effort: 'high' } }
+ ])
+ expect(
+ (
+ await h.host.setOption(h.caller, {
+ envelope: envelope('agentSession.setOption', { key: 'effort', value: 'minimal' }),
+ key: 'effort',
+ value: 'minimal'
+ })
+ ).ok
+ ).toBe(true)
+ const minimal = capture(await h.host.readOptions(HOST_TEST_SESSION))
+ expect(minimal.effort).toBe('minimal')
+ expect((await sendText(h.host, h.caller, 'raw minimal', minimal)).ok).toBe(true)
+ await vi.waitFor(async () =>
+ expect((await h.host.readOptions(HOST_TEST_SESSION)).current).toMatchObject({
+ effort: 'minimal',
+ reportedEffort: 'minimal'
+ })
+ )
+ expect(stateInputs(h.script).slice(-2)).toMatchObject([
+ { command: 'set_thinking_level', params: { level: 'minimal' } },
+ { command: 'prompt', params: { effort: 'minimal' } }
+ ])
+ const journal = await h.host.journalSnapshot(HOST_TEST_SESSION)
+ expect(journal.submissions.map(({ options }) => options?.effort)).toEqual([
+ 'off',
+ 'off',
+ 'off',
+ 'high',
+ 'minimal'
+ ])
+})
+
+it('displays native gapped support and dispatches raw medium for seed and existing-record input', async () => {
+ const model = { ...gpt5, thinkingLevelMap: { medium: null, high: null, xhigh: 'xhigh' } }
+ const models = await readPiRpcModelOptions({ request: async () => ({ models: [model] }) })
+ const h = await setup({
+ create: true,
+ seed: { model: 'openai-codex/gpt-6.1-sol', effort: 'medium' },
+ catalog: models,
+ native: { model, appliedEfforts: { medium: 'xhigh' } },
+ firstMessage: 'raw seed'
+ })
+ expect(h.params.options?.effort).toBe('medium')
+ expect(displayed(await h.host.readOptions(HOST_TEST_SESSION))).toMatchObject({
+ kind: { currentValue: 'xhigh' }
+ })
+ await vi.waitFor(() => expect(h.script.spawns()).toBe(1))
+ h.script.releaseHandshake()
+ await vi.waitFor(() => expect(h.script.prompts()).toHaveLength(1))
+ expect(stateInputs(h.script)).toMatchObject([
+ { command: 'set_model', params: { provider: 'openai-codex', modelId: 'gpt-6.1-sol' } },
+ { command: 'set_thinking_level', params: { level: 'medium' } },
+ { command: 'prompt', params: { effort: 'xhigh' } }
+ ])
+ const store = peekOpenedAgentSessionRecordStore()!
+ await store.replaceSessionOptions({
+ sessionId: HOST_TEST_SESSION,
+ fence: store.getRecord(HOST_TEST_SESSION)!.lease.runtimeFence,
+ options: { model: 'openai-codex/gpt-6.1-sol', effort: 'medium' },
+ now: HOST_TEST_NOW
+ })
+ expect(displayed(await h.host.readOptions(HOST_TEST_SESSION))).toMatchObject({
+ kind: { currentValue: 'xhigh' }
+ })
+ expect((await sendText(h.host, h.caller, 'opaque medium')).ok).toBe(true)
+ await vi.waitFor(() => expect(h.script.prompts()).toHaveLength(2))
+ expect(stateInputs(h.script).at(-1)).toMatchObject({
+ command: 'prompt',
+ params: { effort: 'xhigh' }
+ })
+ expect(
+ stateInputs(h.script).filter(({ command }) => command === 'set_thinking_level')
+ ).toHaveLength(1)
+})
diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-option-state.ts b/src/renderer/src/components/native-chat/use-structured-agent-session-option-state.ts
index 66a72777c59..456656b7c42 100644
--- a/src/renderer/src/components/native-chat/use-structured-agent-session-option-state.ts
+++ b/src/renderer/src/components/native-chat/use-structured-agent-session-option-state.ts
@@ -152,7 +152,8 @@ export function useStructuredAgentSessionOptionState(args: {
...previous,
record: cloneStructuredAgentSessionOptionRecord(previous.record),
pendingId: null,
- reportedPermissionMode: undefined
+ reportedPermissionMode: undefined,
+ reportedEffort: undefined
}
: seeded
const next = sameSession ? { ...kept, permissionMode: previous.permissionMode } : kept
diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-options.first-frame.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-options.first-frame.test.tsx
index c42d0430fa2..88d66968ed6 100644
--- a/src/renderer/src/components/native-chat/use-structured-agent-session-options.first-frame.test.tsx
+++ b/src/renderer/src/components/native-chat/use-structured-agent-session-options.first-frame.test.tsx
@@ -102,6 +102,7 @@ function renderNewChat(args: {
seedOptions?: Record<string, string>
explicitOptions?: Record<string, string>
sessionId?: string
+ restored?: boolean
}) {
const frames: Pill[] = []
const view = renderHook(() => {
@@ -117,7 +118,7 @@ function renderNewChat(args: {
unloadedTurnRevisions: undefined,
mutate: vi.fn(),
launch: {
- kind: 'new',
+ kind: args.restored ? 'resume' : 'new',
worktree: 'id:wt-1',
...(args.explicitOptions ? { explicitOptions: args.explicitOptions } : {}),
...(args.seedOptions ? { seedOptions: args.seedOptions } : {})
@@ -152,6 +153,37 @@ describe('a new chat picker’s first frame', () => {
resetHostModelCatalogSnapshotsForTests()
})
+ it('Pi cached first paint and late precise catalog keep the supported remembered composer value', async () => {
+ const row = {
+ id: 'openai/gpt-5',
+ label: 'GPT-5',
+ isDefault: false,
+ efforts: ['minimal', 'low', 'medium', 'high', 'xhigh', 'max'].map((value) => ({
+ value,
+ label: value
+ }))
+ }
+ const list: Listed = { origin: 'probe', models: [row], fetchedAt: 1 }
+ catalogAnswers(() => Promise.resolve(list))
+ await preloadHostModelCatalogSnapshots(LOCAL_TARGET, ['pi'])
+ const remembered = { model: row.id, effort: 'off' }
+ const first = renderNewChat({ agent: 'pi', seedOptions: remembered })
+ expect(first.frames[0]).toMatchObject({ model: row.id, effort: 'minimal' })
+ expect(
+ first.result.current.optionSnapshot.find((option) => option.id === 'effort')
+ ).toMatchObject({ kind: { currentValue: 'minimal', choices: row.efforts } })
+ first.unmount()
+ resetHostModelCatalogSnapshotsForTests()
+ const next = deferred<AgentSessionModelCatalogResult>()
+ catalogAnswers(() => next.promise)
+ const late = renderNewChat({ agent: 'pi', seedOptions: remembered, restored: true })
+ expect(late.frames[0]).toEqual(PLACEHOLDER)
+ await act(async () => next.resolve(list))
+ await waitFor(() => expect(late.frames.at(-1)?.effort).toBe('minimal'))
+ expect(remembered.effort).toBe('off')
+ late.unmount()
+ })
+
it('shows the unlisted action model rather than a saved or listed replacement on every pending frame', async () => {
catalogAnswers(() => Promise.resolve(CLAUDE_LIST))
await preloadHostModelCatalogSnapshots(LOCAL_TARGET, ['claude'])
diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-options.test-fixture.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-options.test-fixture.tsx
index 41dc078f2c7..09c013b9512 100644
--- a/src/renderer/src/components/native-chat/use-structured-agent-session-options.test-fixture.tsx
+++ b/src/renderer/src/components/native-chat/use-structured-agent-session-options.test-fixture.tsx
@@ -12,7 +12,7 @@ type OptionsFixtureMocks = {
enqueue: Mock
pick: Mock
target: RuntimeClientTarget
- agent: 'codex' | 'claude' | 'antigravity'
+ agent: 'codex' | 'claude' | 'pi' | 'antigravity'
hold: Mock<
(
sessionId: string,
@@ -23,10 +23,14 @@ type OptionsFixtureMocks = {
>
toastError: Mock<(message: string) => void>
coherentCatalog: boolean
+ sendSelection: boolean
}
const mocks: OptionsFixtureMocks = vi.hoisted(() => {
- const selection: { target: RuntimeClientTarget; agent: 'codex' | 'claude' } = {
+ const selection: {
+ target: RuntimeClientTarget
+ agent: 'codex' | 'claude' | 'pi' | 'antigravity'
+ } = {
target: { kind: 'local' },
agent: 'codex'
}
@@ -44,7 +48,8 @@ const mocks: OptionsFixtureMocks = vi.hoisted(() => {
) => Promise<SelectionOutcome> | null
>(),
toastError: vi.fn<(message: string) => void>(),
- coherentCatalog: false
+ coherentCatalog: false,
+ sendSelection: false
}
})
@@ -63,6 +68,7 @@ vi.mock('@/runtime/structured-agent-session-host-capability', async () => {
const supported = actual.useStructuredAgentSessionHostCapability(target, capability)
return (
(mocks.coherentCatalog && capability === 'agent-session.coherent-model-catalog.v1') ||
+ (mocks.sendSelection && capability === 'agent-session.send-selection.v1') ||
supported
)
}
@@ -107,6 +113,7 @@ vi.mock('@/lib/structured-agent-session-launch-options', async () => {
import type { SessionOptionDescriptor } from '../../../../shared/native-chat/input/native-chat-session-options'
import type { StructuredAgentSessionMutate } from './use-structured-agent-session-mutate'
import { useStructuredAgentSessionOptions } from './use-structured-agent-session-options'
+import { useStructuredAgentSessionSendOptions } from './use-structured-agent-session-send-options'
const LOCAL_TARGET = { kind: 'local' } as const
const PAIRED_TARGET = { kind: 'environment', environmentId: 'server-1' } as const
@@ -152,6 +159,7 @@ function mutateWith(reply: MutateCall): {
}
type RenderProps = {
+ sessionId?: string
transportEnabled: boolean
fence: number | null
turnId?: string | null
@@ -159,7 +167,7 @@ type RenderProps = {
hidden?: boolean
launchSeedOptions?: Record<string, string>
worktree?: string
- agent?: 'claude' | 'codex' | 'antigravity'
+ agent?: 'claude' | 'codex' | 'pi' | 'antigravity'
providerStarting?: boolean
paired?: boolean
}
@@ -175,10 +183,10 @@ function renderOptions(initial: RenderProps, mutate: StructuredAgentSessionMutat
mocks.target = initial.paired ? PAIRED_TARGET : LOCAL_TARGET
mocks.agent = initial.agent ?? 'codex'
return renderHook(
- (props: RenderProps) =>
- useStructuredAgentSessionOptions({
+ (props: RenderProps) => {
+ const options = useStructuredAgentSessionOptions({
agent: props.agent ?? 'codex',
- sessionId: 'session-1',
+ sessionId: props.sessionId ?? 'session-1',
target: props.paired ? PAIRED_TARGET : LOCAL_TARGET,
transportEnabled: props.transportEnabled,
isVisible: !props.hidden,
@@ -197,7 +205,14 @@ function renderOptions(initial: RenderProps, mutate: StructuredAgentSessionMutat
}
}
: {})
- }),
+ })
+ const capture = useStructuredAgentSessionSendOptions(
+ props.sessionId ?? 'session-1',
+ undefined,
+ options.sendSource
+ )
+ return { ...options, capture }
+ },
{ initialProps: initial }
)
}
diff --git a/src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx b/src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx
index b4bf557179d..ea7dd34ff46 100644
--- a/src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx
+++ b/src/renderer/src/components/native-chat/use-structured-agent-session-options.test.tsx
@@ -19,11 +19,12 @@ import {
LIVE_OPTIONS,
SAVED_LIST,
SEED,
- tick
+ tick,
+ type RenderProps
} from './use-structured-agent-session-options.test-fixture'
import type { AgentSessionOptionsResult } from '../../../../shared/agent-session-wire'
import { act, waitFor } from '@testing-library/react'
-import { beforeEach, describe, expect, it } from 'vitest'
+import { beforeEach, describe, expect, it, vi } from 'vitest'
import {
structuredAgentSessionSendSelection,
@@ -37,6 +38,7 @@ import { replaceRuntimeEnvironmentRevisions } from '@/runtime/runtime-environmen
import { resetHostModelCatalogSnapshotsForTests } from '@/runtime/host-model-catalog-snapshots'
describe('useStructuredAgentSessionOptions', () => {
beforeEach(() => {
+ mocks.sendSelection = false
forgetStructuredSessionSelection('session-1')
mocks.call.mockReset()
mocks.enqueue.mockReset()
@@ -749,3 +751,96 @@ describe('useStructuredAgentSessionOptions', () => {
}
)
})
+
+import type {
+ PiRefreshFixtureModule,
+ PiRefreshMount
+} from '../../../../shared/structured-agent-session-option-refresh.test-fixture-contract'
+const { piOptionRefreshContract } = await vi.importActual<PiRefreshFixtureModule>(
+ '../../../../main/native-chat/agent-session-wire/structured-agent-session-option-refresh.test-fixture'
+)
+
+describe('Pi catalog refresh completion', () => {
+ beforeEach(() => {
+ replaceRuntimeEnvironmentRevisions([{ id: 'server-1', createdAt: 1 }])
+ mocks.sendSelection = true
+ mocks.call.mockReset()
+ mocks.enqueue.mockReset()
+ mocks.hold.mockReset()
+ resetHostModelCatalogSnapshotsForTests()
+ })
+
+ const hosts = new Map<string, Parameters<PiRefreshMount>[0]>()
+ piOptionRefreshContract(
+ async (host) => {
+ forgetStructuredSessionSelection(host.record.sessionId)
+ hosts.set(host.record.sessionId, host)
+ mocks.call.mockImplementation(
+ (
+ _target: unknown,
+ method: string,
+ params: {
+ sessionId?: string
+ envelope?: { sessionId?: string }
+ key?: string
+ value?: string
+ }
+ ) => {
+ const id = params?.sessionId ?? params?.envelope?.sessionId
+ const current = id ? hosts.get(id) : undefined
+ if (method === 'agentSession.options' && current) {
+ return current.options()
+ }
+ if (method === 'agentSession.modelCatalog' && current) {
+ return current.catalog()
+ }
+ if (
+ method === 'agentSession.setOption' &&
+ current &&
+ params.key === 'effort' &&
+ typeof params.value === 'string'
+ ) {
+ return current.acceptEffort(params.value).then((value) => ({ ok: true, value }))
+ }
+ return new Promise(() => {})
+ }
+ )
+ const { mutate } = mutateWith(async (_method, _fingerprint, fields) => {
+ if (
+ typeof fields !== 'object' ||
+ fields === null ||
+ !('value' in fields) ||
+ typeof fields.value !== 'string'
+ ) {
+ throw new Error('missing effort')
+ }
+ return host.acceptEffort(fields.value)
+ })
+ const props: RenderProps = { ...REOPENED, agent: 'pi', sessionId: host.record.sessionId }
+ const harness = renderOptions(props, mutate)
+ await act(async () => {
+ await Promise.resolve()
+ })
+ return {
+ snapshot: () => harness.result.current.optionSnapshot,
+ capture: () => harness.result.current.capture().selection,
+ demand: () => harness.result.current.optionSurface.demandModelCatalog?.(),
+ pick: (value) => harness.result.current.setStructuredOption('effort', value),
+ replace: async (fence, otherHost) => {
+ await act(async () => harness.rerender({ ...props, fence, paired: otherHost }))
+ },
+ close: async () => {
+ harness.unmount()
+ hosts.delete(host.record.sessionId)
+ }
+ }
+ },
+ async (work) => {
+ await act(async () => {
+ work()
+ await Promise.resolve()
+ await Promise.resolve()
+ })
+ }
+ )
+})
diff --git a/src/renderer/src/lib/structured-agent-session-launch-create-message.ts b/src/renderer/src/lib/structured-agent-session-launch-create-message.ts
index e6a734eb388..d80a20e66b2 100644
--- a/src/renderer/src/lib/structured-agent-session-launch-create-message.ts
+++ b/src/renderer/src/lib/structured-agent-session-launch-create-message.ts
@@ -114,10 +114,10 @@ function structuredLaunchCreateOptions(state: StructuredLaunchState): {
state.selection.explicit
)
const drawn = structuredAgentSessionDrawnValues(view)
- // Each held value as the picker draws it; the held picks themselves stay as the user made them.
+ // Model and effort remain raw action input; tier retains its existing display projection.
const held = Object.fromEntries(
Object.entries(overlay).map(([id, encoded]) => {
- const value = id === 'model' ? undefined : drawn[id]?.value
+ const value = id === 'model' || id === 'effort' ? undefined : drawn[id]?.value
const shown = value === undefined ? null : encodeStructuredAgentSessionOptionValue(id, value)
return [id, shown ?? encoded]
})
diff --git a/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts b/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts
index 7f64900f035..1b55fe09ed4 100644
--- a/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts
+++ b/src/renderer/src/lib/structured-agent-session-launch-resume-identity.test.ts
@@ -4,6 +4,8 @@
// the identity under test is derived there — mocking it out would assert only the mock's shape.
import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { recordHostModelCatalogSnapshot } from '@/runtime/host-model-catalog-snapshots'
+import { holdStructuredAgentSessionLaunchOption } from './structured-agent-session-launch-options'
import type { StructuredAgentSessionCreateParams } from '../../../shared/structured-agent-session-create'
const mocks = vi.hoisted(() => ({
@@ -24,7 +26,10 @@ vi.mock('@/lib/agent-catalog', () => ({
}))
vi.mock('@/runtime/structured-agent-session-client', () => ({
- callStructuredAgentSession: mocks.call
+ callStructuredAgentSession: mocks.call,
+ supportsStructuredAgentSessionCreateMessage: async () => true,
+ supportsStructuredAgentSessionCreateOptionsMode: async () => true,
+ structuredAgentSessionHostSupports: async () => true
}))
vi.mock('@/runtime/local-structured-session-tabs-sync/inventory-refresh', () => ({
@@ -75,6 +80,42 @@ describe('a launch that adopts a conversation is its own identity', () => {
})
})
+ it.each(['off', 'medium'])(
+ 'keeps held Pi %s raw in first-message identity despite supported drawing',
+ async (effort) => {
+ recordHostModelCatalogSnapshot({ kind: 'local' }, 'pi', null, {
+ origin: 'probe',
+ fetchedAt: 1,
+ models: [
+ {
+ id: 'openai/gpt-5',
+ label: 'GPT-5',
+ isDefault: false,
+ efforts: ['off', 'minimal', 'low', 'xhigh']
+ .filter((value) => effort !== 'off' || value !== 'off')
+ .map((value) => ({ value, label: value }))
+ }
+ ]
+ })
+ const launch = startStructuredAgentLaunch(`held-pi-${effort}`, 'pi', {
+ requestId: `held-pi-${effort}`,
+ prompt: 'opening text'
+ })
+ holdStructuredAgentSessionLaunchOption(launch.sessionId, 'model', 'openai/gpt-5')
+ holdStructuredAgentSessionLaunchOption(launch.sessionId, 'effort', effort)
+ await flushLaunchDispatch()
+ await vi.waitFor(() => expect(createParams()).toHaveLength(1))
+ expect(createParams()[0]?.firstMessage?.body.blocks).toEqual([
+ { type: 'text', text: 'opening text' }
+ ])
+ expect(createParams()[0]?.options).toEqual({ model: 'openai/gpt-5', effort })
+ expect(createParams()[0]?.firstMessage?.selection).toMatchObject({
+ model: 'openai/gpt-5',
+ effort
+ })
+ }
+ )
+
it('does not hand a resume the blank launch already pending for the same worktree', async () => {
// Joiners inherit existing intent and add prompt only; joining a blank launch would discard conversation adoption.
const worktreeId = 'wt-resume-vs-blank'
diff --git a/src/shared/agent-session-options-result.ts b/src/shared/agent-session-options-result.ts
index 9930fbc7f73..5aa98c29e36 100644
--- a/src/shared/agent-session-options-result.ts
+++ b/src/shared/agent-session-options-result.ts
@@ -36,6 +36,8 @@ export type AgentSessionOptionsResult = {
acceptedInputSources?: AgentSessionAcceptedInputSources
model?: string
effort?: string
+ /** Child-scoped actual for display only; effort remains accepted raw input. */
+ reportedEffort?: string
/** Canonical preference for the next turn. Explicit false is meaningful. */
fastMode?: boolean
/** Next-turn service tier id where the model lists `serviceTiers`; `default` is standard. */
diff --git a/src/shared/structured-agent-session-discovered-model.ts b/src/shared/structured-agent-session-discovered-model.ts
index fe39a5bcd1b..4a330ad5446 100644
--- a/src/shared/structured-agent-session-discovered-model.ts
+++ b/src/shared/structured-agent-session-discovered-model.ts
@@ -2,7 +2,7 @@ import type { CatalogModel, CatalogOption } from './agent-session-option-catalog
import type { AgentSessionOptionChoice, AgentSessionOptionsResult } from './agent-session-wire'
function effortOption(model: AgentSessionOptionsResult['models'][number]): CatalogOption | null {
- if (model.efforts.length === 0) {
+ if (model.effortsKnown === false || model.efforts.length === 0) {
return null
}
return {
diff --git a/src/shared/structured-agent-session-effective-effort.ts b/src/shared/structured-agent-session-effective-effort.ts
new file mode 100644
index 00000000000..642e8976ef7
--- /dev/null
+++ b/src/shared/structured-agent-session-effective-effort.ts
@@ -0,0 +1,31 @@
+import type { CatalogOption } from './agent-session-option-catalog'
+
+export const PI_THINKING_LEVELS: readonly string[] = [
+ 'off',
+ 'minimal',
+ 'low',
+ 'medium',
+ 'high',
+ 'xhigh',
+ 'max'
+] as const
+const rank = (level: string): number => PI_THINKING_LEVELS.indexOf(level === 'none' ? 'off' : level)
+
+export function catalogEffortLevels(controls: readonly CatalogOption[]): string[] | undefined {
+ const effort = controls.find((option) => option.id === 'effort')
+ return effort?.kind.type === 'select'
+ ? effort.kind.choices.map((choice) => choice.value)
+ : undefined
+}
+
+/** Pi uses higher-first, then lower; unknown support preserves opaque intent. */
+export function effectiveAgentEffort(
+ effort: string | undefined,
+ supported: readonly string[] | undefined
+): string | undefined {
+ if (!effort || !supported?.length || supported.includes(effort) || rank(effort) === -1) {
+ return effort
+ }
+ const ranked = supported.filter((level) => rank(level) !== -1).sort((a, b) => rank(a) - rank(b))
+ return ranked.find((level) => rank(level) >= rank(effort)) ?? ranked.at(-1) ?? effort
+}
diff --git a/src/shared/structured-agent-session-option-refresh.test-fixture-contract.ts b/src/shared/structured-agent-session-option-refresh.test-fixture-contract.ts
new file mode 100644
index 00000000000..a2a30da8d5a
--- /dev/null
+++ b/src/shared/structured-agent-session-option-refresh.test-fixture-contract.ts
@@ -0,0 +1,29 @@
+import type {
+ AgentSessionModelCatalogResult,
+ AgentSessionOptionResult,
+ AgentSessionOptionsResult
+} from './agent-session-wire'
+import type { SessionOptionDescriptor } from './native-chat/input/native-chat-session-options'
+
+export type PiRefreshHarness = {
+ snapshot: () => readonly SessionOptionDescriptor[]
+ capture: () => Readonly<Record<string, string>> | undefined
+ demand: () => void
+ pick: (value: string) => Promise<boolean>
+ replace: (fence: number, otherHost?: boolean) => Promise<void>
+ close: () => Promise<void>
+}
+
+export type PiRefreshMount = (host: {
+ record: { sessionId: string }
+ options: () => Promise<AgentSessionOptionsResult>
+ catalog: () => Promise<AgentSessionModelCatalogResult>
+ acceptEffort: (value: string) => Promise<AgentSessionOptionResult>
+}) => Promise<PiRefreshHarness>
+
+export type PiRefreshFixtureModule = {
+ piOptionRefreshContract: (
+ mount: PiRefreshMount,
+ flush: (work: () => void) => Promise<void>
+ ) => void
+}
diff --git a/src/shared/structured-agent-session-option-snapshot.ts b/src/shared/structured-agent-session-option-snapshot.ts
index effb0c43e8a..4b31e830ada 100644
--- a/src/shared/structured-agent-session-option-snapshot.ts
+++ b/src/shared/structured-agent-session-option-snapshot.ts
@@ -13,6 +13,10 @@ import type {
SessionOptionValue
} from './native-chat/input/native-chat-session-options'
import type { TrackedNativeChatSessionOption } from './native-chat/input/native-chat-session-option-state'
+import {
+ catalogEffortLevels,
+ effectiveAgentEffort
+} from './structured-agent-session-effective-effort'
import { effectiveServiceTier } from './structured-agent-session-effective-tier'
import { serviceTierOption } from './structured-agent-session-discovered-model'
import {
@@ -130,9 +134,24 @@ function drawnModelControls(state: StructuredAgentSessionOptionState) {
const normalises =
shown.shown.currentId !== null &&
structuredAgentSessionDescribedModel(state, shown.shown.currentId) !== undefined
- const values = normalises
+ let values = normalises
? valuesUnderControls(catalog, controls, record.values, state.olderHost === true)
: record.values
+ if (record.agent === 'pi' && state.reportedEffort !== undefined) {
+ values = { ...values, effort: { value: state.reportedEffort, source: 'reported' } }
+ }
+ const requested = values.effort
+ if (
+ normalises &&
+ record.agent === 'pi' &&
+ typeof requested?.value === 'string' &&
+ requested.source !== 'reported'
+ ) {
+ const effort = effectiveAgentEffort(requested.value, catalogEffortLevels(controls))
+ if (effort && effort !== requested.value) {
+ values = { ...values, effort: { ...requested, value: effort } }
+ }
+ }
return { catalog, models, ...shown, controls, values }
}
@@ -164,7 +183,6 @@ function modelOptionSnapshot(state: StructuredAgentSessionOptionState): SessionO
return [PROVIDER_DEFAULT_MODEL_PLACEHOLDER]
}
const { catalog, models, shown, controlsModelId, isCliDefault, controls, values } = drawn
- const { record } = state
const snapshot =
models.length === 0
? []
@@ -183,9 +201,10 @@ function modelOptionSnapshot(state: StructuredAgentSessionOptionState): SessionO
? withUnlistedEffort(
catalog,
controlsModelId,
- record.values.effort,
+ values.effort,
state.verifiedModelIds,
- snapshot
+ snapshot,
+ state.record.agent
)
: [PROVIDER_DEFAULT_MODEL_PLACEHOLDER]
}
diff --git a/src/shared/structured-agent-session-option-view.test.ts b/src/shared/structured-agent-session-option-view.test.ts
index cc234da4fe1..de3fc71990f 100644
--- a/src/shared/structured-agent-session-option-view.test.ts
+++ b/src/shared/structured-agent-session-option-view.test.ts
@@ -1,9 +1,11 @@
+import { structuredAgentSessionSeedCatalog } from './structured-agent-session-seed-catalog'
import { describe, expect, it } from 'vitest'
import { CLAUDE_SESSION_OPTION_CATALOG } from './agent-session-option-catalog-claude-codex'
import type { AgentSessionModelCatalogResult } from './agent-session-wire'
import {
applyStructuredAgentSessionModelCatalog,
applyStructuredAgentSessionOptions,
+ canSetStructuredAgentSessionOption,
commitStructuredAgentSessionOption,
createStructuredAgentSessionOptionState,
structuredAgentSessionOptionSnapshot,
@@ -210,6 +212,131 @@ describe("a chat's model and effort, apart from the defaults filling them in", (
})
})
+describe('Pi supported selection apart from saved intent', () => {
+ const seed = structuredAgentSessionSeedCatalog('pi')
+ const remembered = { model: 'openai/gpt-5', effort: 'off' }
+ const row = {
+ id: remembered.model,
+ label: 'GPT-5',
+ isDefault: false,
+ efforts: levels('minimal', 'low', 'medium', 'high')
+ }
+ const catalog = (efforts = row.efforts) => ({
+ origin: 'probe' as const,
+ models: [{ ...row, efforts }],
+ fetchedAt: 1
+ })
+ const fresh = () => createStructuredAgentSessionOptionState('pi', seed)
+ const install = (state = fresh(), efforts = row.efforts) =>
+ applyStructuredAgentSessionModelCatalog(state, seed, catalog(efforts), { newLaunch: true })
+ const effort = (state: StructuredAgentSessionOptionState) =>
+ structuredAgentSessionShownSnapshot(state).find((option) => option.id === 'effort')
+
+ it('rederives new and restored blank controls on a late precise row and readback without restoring off', () => {
+ const coarse = install(fresh(), levels('off', 'minimal', 'low', 'medium', 'high'))
+ expect(shown(coarse, remembered, {})).toEqual(remembered)
+ const precise = install(coarse)
+ const newView = structuredAgentSessionOptionView(precise, remembered, {})
+ const restored = applyStructuredAgentSessionOptions(install(), seed, {
+ models: [row],
+ listedModelIds: [row.id],
+ current: remembered
+ })
+ const readback = applyStructuredAgentSessionOptions(restored, seed, {
+ models: [row],
+ listedModelIds: [row.id],
+ current: { ...remembered, effort: 'minimal', confirmed: ['model', 'effort'] }
+ })
+ for (const state of [newView, restored, readback]) {
+ expect(effort(state)).toMatchObject({
+ kind: { currentValue: 'minimal', choices: row.efforts },
+ settable: true
+ })
+ expect(canSetStructuredAgentSessionOption(state, 'effort', 'off')).toBe(true)
+ expect(canSetStructuredAgentSessionOption(state, 'effort', 'minimal')).toBe(true)
+ expect(structuredAgentSessionSendSelection(state)).toBeUndefined()
+ }
+ expect(remembered.effort).toBe('off')
+ expect(precise.record.values).toEqual({})
+ })
+
+ it('uses native policy for seeds and ordinary input, and keeps actual/unknown evidence honest', () => {
+ const gapped = { ...row, efforts: levels('off', 'minimal', 'low', 'xhigh') }
+ const state = install(fresh(), gapped.efforts)
+ expect(shown(state, { ...remembered, effort: 'medium' }, {})).toMatchObject({ effort: 'xhigh' })
+ const ordinary = applyStructuredAgentSessionOptions(state, seed, {
+ models: [gapped],
+ current: {
+ ...remembered,
+ effort: 'medium',
+ acceptedInputSources: { model: 'saved', effort: 'saved' }
+ }
+ })
+ expect(effort(ordinary)).toMatchObject({
+ kind: { currentValue: 'xhigh', choices: gapped.efforts }
+ })
+ expect(structuredAgentSessionMessageSelection(ordinary).effort).toBe('medium')
+ const actual = applyStructuredAgentSessionOptions(install(), seed, {
+ models: [row],
+ current: {
+ ...remembered,
+ reportedEffort: 'future',
+ acceptedInputSources: { model: 'saved', effort: 'saved' }
+ }
+ })
+ expect(structuredAgentSessionMessageSelection(actual)).toEqual(remembered)
+
+ expect(effort(actual)).toMatchObject({
+ settable: false,
+ kind: { currentValue: 'future', choices: [{ value: 'future', label: 'future' }] }
+ })
+ const cleared = applyStructuredAgentSessionOptions(install(), seed, {
+ models: [row],
+ current: { ...remembered, reportedEffort: 'low', acceptedInputSources: {} }
+ })
+ expect(structuredAgentSessionMessageSelection(cleared)).toEqual({})
+ const absent = applyStructuredAgentSessionOptions(cleared, seed, {
+ models: [row],
+ current: remembered
+ })
+ expect(absent.reportedEffort).toBeUndefined()
+ expect(structuredAgentSessionMessageSelection(absent)).toEqual(remembered)
+ const equal = commitStructuredAgentSessionOption(actual, 'effort', 'off')
+ expect(equal.reportedEffort).toBeUndefined()
+ expect(effort(equal)?.kind.currentValue).toBe('minimal')
+ const future = commitStructuredAgentSessionOption(equal, 'effort', 'high')
+ expect(effort(future)?.kind.currentValue).toBe('high')
+ expect(structuredAgentSessionMessageSelection(future).effort).toBe('high')
+
+ const unknown = applyStructuredAgentSessionOptions(install(), seed, {
+ models: [{ ...row, effortsKnown: false }],
+ current: remembered
+ })
+ expect(effort(unknown)).toMatchObject({ settable: false, kind: { currentValue: 'off' } })
+ })
+
+ it('bounds projection work by the existing model rows at N and 10N without population subscriptions', () => {
+ const work = (size: number) => {
+ let reads = 0
+ const state = install()
+ const controls = state.catalog!.models[0]!.options
+ state.catalog!.models = Array.from({ length: size }, (_, index) => ({
+ get id() {
+ reads += 1
+ return index === size - 1 ? row.id : `other-${index}`
+ },
+ label: 'Model',
+ options: controls
+ }))
+ const view = structuredAgentSessionOptionView(state, remembered, {})
+ expect(effort(view)).toMatchObject({ kind: { currentValue: 'minimal' } })
+ return reads
+ }
+ const small = work(61)
+ expect(work(610)).toBeLessThanOrEqual(10 * small)
+ })
+})
+
it('bounds exact capture by catalog width at N and 10N', () => {
const work: number[] = []
for (const count of [10, 100]) {
diff --git a/src/shared/structured-agent-session-option-view.ts b/src/shared/structured-agent-session-option-view.ts
index ac8fd4885c4..cc21d223bfb 100644
--- a/src/shared/structured-agent-session-option-view.ts
+++ b/src/shared/structured-agent-session-option-view.ts
@@ -130,7 +130,12 @@ export function structuredAgentSessionMessageSelection(
) {
continue
}
+ const raw =
+ view.record.agent === 'pi' && (id === 'model' || id === 'effort')
+ ? view.record.values[id]?.value
+ : undefined
const value =
+ raw ??
descriptor?.kind.currentValue ??
(view.acceptedInputSources !== undefined ? view.record.values[id]?.value : undefined)
if (value !== undefined) {
diff --git a/src/shared/structured-agent-session-options.ts b/src/shared/structured-agent-session-options.ts
index e060e8294fb..73020c8fd26 100644
--- a/src/shared/structured-agent-session-options.ts
+++ b/src/shared/structured-agent-session-options.ts
@@ -66,6 +66,7 @@ export type StructuredAgentSessionOptionState = {
permissionMode: string | null
reportedPermissionMode?: string | null
permissionOwnSupported?: boolean | null
+ reportedEffort?: string
pendingId: string | null
listingInProgress?: boolean
fastModeRestricted?: boolean
@@ -203,6 +204,7 @@ export function applyStructuredAgentSessionOptions(
return {
...state,
optionsAnswerPresent: true,
+ reportedEffort: state.record.agent === 'pi' ? current.reportedEffort : undefined,
catalog: installed ? state.catalog : structuredAgentSessionOptionCatalog(seed, result),
fastModeRestricted:
installed &&
@@ -238,6 +240,9 @@ export function commitStructuredAgentSessionOption(
value: string,
origin: 'picked' | 'seeded' = 'picked'
): StructuredAgentSessionOptionState {
+ if (id === 'model' || id === 'effort') {
+ state = { ...state, reportedEffort: undefined }
+ }
if (id === AGENT_CHAT_PERMISSION_MODE_OPTION_ID) {
return { ...state, permissionMode: value, reportedPermissionMode: undefined, pendingId: null }
}
diff --git a/src/shared/structured-agent-session-unlisted-effort.ts b/src/shared/structured-agent-session-unlisted-effort.ts
index 70549aef528..d6ed754925d 100644
--- a/src/shared/structured-agent-session-unlisted-effort.ts
+++ b/src/shared/structured-agent-session-unlisted-effort.ts
@@ -1,3 +1,4 @@
+import type { AgentType } from './agent-status-types'
import type { AgentSessionOptionCatalog } from './agent-session-option-catalog'
import type { SessionOptionDescriptor } from './native-chat/input/native-chat-session-options'
import type { TrackedNativeChatSessionOption } from './native-chat/input/native-chat-session-option-state'
@@ -10,11 +11,14 @@ export function withUnlistedEffort(
effort: TrackedNativeChatSessionOption | undefined,
/** The ids the chat's own options answer lists; absent from an older host. */
listed: readonly string[] | undefined,
- snapshot: SessionOptionDescriptor[]
+ snapshot: SessionOptionDescriptor[],
+ agent: AgentType
): SessionOptionDescriptor[] {
+ if (!modelId || typeof effort?.value !== 'string') {
+ return snapshot
+ }
if (
- !modelId ||
- typeof effort?.value !== 'string' ||
+ agent !== 'pi' &&
snapshot.some(
(entry) =>
entry.id === 'effort' &&
@@ -28,7 +32,7 @@ export function withUnlistedEffort(
.find((model) => model.id === modelId)
?.options.find((option) => option.id === 'effort')
if (
- listed?.includes(modelId) &&
+ (listed?.includes(modelId) || (agent === 'pi' && !listed)) &&
offered?.kind.type === 'select' &&
offered.kind.choices.some((choice) => choice.value === effort.value)
) {