mirror of
https://github.com/stablyai/orca.git
synced 2026-11-19 04:23:57 +00:00
Keep the saved model when reopening ACP chats (#38815)
* Preserve native model choice when restoring ACP chats * Forward startup observations through the OpenCode connection * Use fixed time in the connection regression fixture * Complete the model-command fixture session identity
This commit is contained in:
@@ -29,7 +29,14 @@ export async function applyAcpMessageOptions(
|
||||
}
|
||||
for (const key of ['model', 'effort'] as const) {
|
||||
const value = options[key]
|
||||
if (value === undefined || session.options.appliedInput.get(key) === value) {
|
||||
if (
|
||||
value === undefined ||
|
||||
session.options.appliedInput.get(key) === value ||
|
||||
(key === 'model' &&
|
||||
(options.effort === undefined ||
|
||||
session.options.appliedInput.get('effort') === options.effort) &&
|
||||
session.options.matchesNativeRestoredModel(value))
|
||||
) {
|
||||
continue
|
||||
}
|
||||
try {
|
||||
|
||||
@@ -54,7 +54,10 @@ const event = (update: SessionUpdate): AcpSessionEvent => ({
|
||||
function rig(updates: SessionUpdate[], version = '18.15.0') {
|
||||
const options = new AcpStructuredOptions(OMP_ACP_DIALECT)
|
||||
options.adoptSession({ configOptions: config('p/a', 'low') }, 'loaded')
|
||||
const lane = { translator: { sessionEvent: vi.fn(() => []) }, apply: vi.fn() }
|
||||
const lane = {
|
||||
translator: { providerSessionId: 'omp-1', sessionEvent: vi.fn(() => []) },
|
||||
apply: vi.fn()
|
||||
}
|
||||
const prompt = vi.fn(async () => {
|
||||
for (const update of updates) {
|
||||
// oxlint-disable-next-line typescript/consistent-type-assertions -- SAFETY: routing reads only the lane's translator and apply, which this fake provides.
|
||||
|
||||
@@ -8,7 +8,8 @@ export function callAcpSession<T>(
|
||||
method: string,
|
||||
params: unknown,
|
||||
schema: z.ZodType<T>,
|
||||
answered: ((signedIn: boolean) => void) | undefined
|
||||
answered: ((signedIn: boolean) => void) | undefined,
|
||||
received?: (response: T) => void
|
||||
): Promise<T> {
|
||||
return peer.request(method, params, {
|
||||
...acpStepBound(method),
|
||||
@@ -32,6 +33,7 @@ export function callAcpSession<T>(
|
||||
if (['session/new', 'session/load', 'session/resume'].includes(method)) {
|
||||
answered?.(true)
|
||||
}
|
||||
received?.(parsed.data)
|
||||
return parsed.data
|
||||
}
|
||||
})
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import {
|
||||
SessionConfigSelectGroupSchema,
|
||||
SessionConfigSelectOptionSchema,
|
||||
type SessionConfigOption,
|
||||
type SessionConfigSelectOption
|
||||
} from './generated/acp-protocol.generated'
|
||||
|
||||
type SelectOption = Extract<SessionConfigOption, { type: 'select' }>
|
||||
|
||||
export function acpSelectChoices(option: SelectOption): SessionConfigSelectOption[] {
|
||||
const choices: SessionConfigSelectOption[] = []
|
||||
for (const entry of option.options) {
|
||||
const group = SessionConfigSelectGroupSchema.safeParse(entry)
|
||||
if (group.success) {
|
||||
choices.push(...group.data.options)
|
||||
continue
|
||||
}
|
||||
const choice = SessionConfigSelectOptionSchema.safeParse(entry)
|
||||
if (choice.success) {
|
||||
choices.push(choice.data)
|
||||
}
|
||||
}
|
||||
return choices
|
||||
}
|
||||
@@ -171,20 +171,25 @@ export class AcpSessionRuntime {
|
||||
/** Requires advertised session deletion support. */
|
||||
deleteSession = (sessionId: string) => this.call('session/delete', { sessionId }, z.unknown())
|
||||
|
||||
start(options: AcpSessionStartOptions): Promise<AcpSessionStarted> {
|
||||
start(
|
||||
options: AcpSessionStartOptions,
|
||||
received?: (started: AcpSessionStarted) => void
|
||||
): Promise<AcpSessionStarted> {
|
||||
if (this.started) {
|
||||
return Promise.resolve(this.started)
|
||||
}
|
||||
this.starting ??= this.initialize()
|
||||
.then((initialized) =>
|
||||
setupAcpSession(initialized, options, (method, params, schema) =>
|
||||
this.call(method, params, schema)
|
||||
setupAcpSession(
|
||||
initialized,
|
||||
options,
|
||||
(method, params, schema, accepted) => this.call(method, params, schema, accepted),
|
||||
(started) => {
|
||||
received?.(started)
|
||||
this.started = started
|
||||
}
|
||||
)
|
||||
)
|
||||
.then((started) => {
|
||||
this.started = started
|
||||
return started
|
||||
})
|
||||
.catch((error) => {
|
||||
this.starting = undefined
|
||||
throw error
|
||||
@@ -233,25 +238,20 @@ export class AcpSessionRuntime {
|
||||
async setConfigOption(
|
||||
configId: SetSessionConfigOptionRequest['configId'],
|
||||
value: SetSessionConfigOptionRequest['value'],
|
||||
meta?: Meta
|
||||
meta?: Meta,
|
||||
received?: (response: SetSessionConfigOptionResponse) => void
|
||||
): Promise<SetSessionConfigOptionResponse> {
|
||||
const sessionId = this.sessionId()
|
||||
const params = { configId, sessionId: this.sessionId(), ...withMeta(meta) }
|
||||
const request =
|
||||
typeof value === 'boolean'
|
||||
? ({
|
||||
configId,
|
||||
value,
|
||||
sessionId,
|
||||
type: 'boolean',
|
||||
...withMeta(meta)
|
||||
} satisfies SetSessionConfigOptionRequest)
|
||||
: ({
|
||||
configId,
|
||||
value,
|
||||
sessionId,
|
||||
...withMeta(meta)
|
||||
} satisfies SetSessionConfigOptionRequest)
|
||||
return this.call('session/set_config_option', request, SetSessionConfigOptionResponseSchema)
|
||||
? ({ ...params, value, type: 'boolean' } satisfies SetSessionConfigOptionRequest)
|
||||
: ({ ...params, value } satisfies SetSessionConfigOptionRequest)
|
||||
return this.call(
|
||||
'session/set_config_option',
|
||||
request,
|
||||
SetSessionConfigOptionResponseSchema,
|
||||
received
|
||||
)
|
||||
}
|
||||
|
||||
close(error?: Error): void {
|
||||
@@ -270,8 +270,13 @@ export class AcpSessionRuntime {
|
||||
return this.started.sessionId
|
||||
}
|
||||
|
||||
private call<T>(method: string, params: unknown, schema: z.ZodType<T>): Promise<T> {
|
||||
return callAcpSession(this.peer, method, params, schema, this.options.onAuthAnswered)
|
||||
private call<T>(
|
||||
method: string,
|
||||
params: unknown,
|
||||
schema: z.ZodType<T>,
|
||||
received?: (response: T) => void
|
||||
): Promise<T> {
|
||||
return callAcpSession(this.peer, method, params, schema, this.options.onAuthAnswered, received)
|
||||
}
|
||||
|
||||
private handleRequest(method: string, params: unknown, context: AcpRequestContext): unknown {
|
||||
|
||||
@@ -29,17 +29,25 @@ export type AcpSessionStartOptions = NewSessionRequest & {
|
||||
resumePreference?: 'load' | 'resume'
|
||||
authMethodId?: string
|
||||
}
|
||||
type Request = <T>(method: string, params: unknown, schema: z.ZodType<T>) => Promise<T>
|
||||
type Request = <T>(
|
||||
method: string,
|
||||
params: unknown,
|
||||
schema: z.ZodType<T>,
|
||||
received?: (response: T) => void
|
||||
) => Promise<T>
|
||||
|
||||
export async function setupAcpSession(
|
||||
initialized: InitializeResponse,
|
||||
options: AcpSessionStartOptions,
|
||||
request: Request
|
||||
request: Request,
|
||||
received?: (started: AcpSessionStarted) => void
|
||||
): Promise<AcpSessionStarted> {
|
||||
const setup = async (): Promise<AcpSessionStarted> => {
|
||||
const { sessionId, resumePreference, authMethodId: _auth, ...params } = options
|
||||
if (sessionId === undefined) {
|
||||
const response = await request('session/new', params, newSessionSchema)
|
||||
const response = await request('session/new', params, newSessionSchema, (response) =>
|
||||
received?.({ kind: 'new', sessionId: response.sessionId, response })
|
||||
)
|
||||
return { kind: 'new', sessionId: response.sessionId, response }
|
||||
}
|
||||
const capabilities = initialized.agentCapabilities
|
||||
@@ -49,14 +57,24 @@ export async function setupAcpSession(
|
||||
return {
|
||||
kind: 'load',
|
||||
sessionId,
|
||||
response: await request('session/load', { ...params, sessionId }, loadSessionSchema)
|
||||
response: await request(
|
||||
'session/load',
|
||||
{ ...params, sessionId },
|
||||
loadSessionSchema,
|
||||
(response) => received?.({ kind: 'load', sessionId, response })
|
||||
)
|
||||
}
|
||||
}
|
||||
if (resume) {
|
||||
return {
|
||||
kind: 'resume',
|
||||
sessionId,
|
||||
response: await request('session/resume', { ...params, sessionId }, resumeSessionSchema)
|
||||
response: await request(
|
||||
'session/resume',
|
||||
{ ...params, sessionId },
|
||||
resumeSessionSchema,
|
||||
(response) => received?.({ kind: 'resume', sessionId, response })
|
||||
)
|
||||
}
|
||||
}
|
||||
throw new AcpRpcError(-32601, 'ACP agent cannot load or resume this session')
|
||||
|
||||
@@ -76,16 +76,27 @@ export async function initializeAcpStructuredSession(
|
||||
let liveLane: AcpStructuredLane | null = null
|
||||
let takeover: ReturnType<typeof acpReopenTakeover> | null = null
|
||||
let replayed: AcpLoadHistoryFrame[] | null = null
|
||||
const acceptSession = (accepted: NonNullable<typeof started>): void => {
|
||||
assertStarting()
|
||||
if (accepted.kind === 'new') {
|
||||
liveLane = input.lanes.create(accepted.sessionId)
|
||||
assertStarting()
|
||||
}
|
||||
options.adoptSession(accepted.response, accepted.kind === 'new' ? 'new' : 'loaded')
|
||||
}
|
||||
if (resume) {
|
||||
const attaching = input.lanes.create(resume.sessionId, true)
|
||||
liveLane = attaching
|
||||
try {
|
||||
started = await connection.start({
|
||||
cwd: launch.cwd,
|
||||
mcpServers: [],
|
||||
sessionId: resume.sessionId,
|
||||
...setup
|
||||
})
|
||||
started = await connection.start(
|
||||
{
|
||||
cwd: launch.cwd,
|
||||
mcpServers: [],
|
||||
sessionId: resume.sessionId,
|
||||
...setup
|
||||
},
|
||||
acceptSession
|
||||
)
|
||||
assertStarting()
|
||||
replayed = input.lanes.finishLoad()
|
||||
attaching.translator.finishLoad()
|
||||
@@ -101,9 +112,11 @@ export async function initializeAcpStructuredSession(
|
||||
if (!started || !liveLane) {
|
||||
liveLane?.dispose()
|
||||
input.lanes.clear()
|
||||
started = await connection.start({ cwd: launch.cwd, mcpServers: [], ...setup })
|
||||
started = await connection.start({ cwd: launch.cwd, mcpServers: [], ...setup }, acceptSession)
|
||||
assertStarting()
|
||||
liveLane = input.lanes.create(started.sessionId)
|
||||
}
|
||||
if (!liveLane) {
|
||||
throw new Error('ACP session did not open')
|
||||
}
|
||||
// Only a load that reopened the chat's own conversation catches up, and only from what that
|
||||
// conversation replayed; a replacement session has no history of the chat's to add.
|
||||
@@ -130,22 +143,20 @@ export async function initializeAcpStructuredSession(
|
||||
}
|
||||
const childStops = await probeAcpChildStops(connection, spec.dialect)
|
||||
assertStarting()
|
||||
options.adoptSession(started.response, started.kind === 'new' ? 'new' : 'loaded')
|
||||
liveLane.apply(liveLane.translator.contextModels(started.response.models, now()))
|
||||
const mode = spec.permissionModeConfig
|
||||
if (mode && acquire.permissionMode !== 'own') {
|
||||
// Fail startup rather than silently use a different permission mode.
|
||||
const requested = mode.values[acquire.permissionMode ?? 'ask'] ?? mode.values.ask
|
||||
const configId = options.modeConfigId()
|
||||
const { configOptions } = await connection.setConfigOption(configId, requested)
|
||||
await connection.setConfigOption(configId, requested, undefined, ({ configOptions }) => {
|
||||
assertStarting()
|
||||
if (configOptions.find((option) => option.id === configId)?.currentValue !== requested) {
|
||||
throw new Error('Permission mode could not be confirmed')
|
||||
}
|
||||
options.adoptConfigOptions(configOptions)
|
||||
})
|
||||
assertStarting()
|
||||
if (configOptions.find((option) => option.id === configId)?.currentValue !== requested) {
|
||||
throw new Error('Permission mode could not be confirmed')
|
||||
}
|
||||
options.adoptSession(
|
||||
{ ...started.response, configOptions },
|
||||
started.kind === 'new' ? 'new' : 'loaded'
|
||||
)
|
||||
}
|
||||
// A load restores the conversation's own model, so only a new session runs the launch choice.
|
||||
if (started.kind === 'new' && launch.launchModel) {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { acpSelectChoices } from './acp-select-choices'
|
||||
import { acpInitializeForkSupport } from './acp-fork-support'
|
||||
import type {
|
||||
AgentSessionModelOption,
|
||||
@@ -13,14 +14,11 @@ import {
|
||||
type AgentModelCatalogConfiguredChoice,
|
||||
type AgentModelCatalogLiveListing
|
||||
} from '../native-chat/agent-model-catalog/agent-model-catalog-entry'
|
||||
import {
|
||||
SessionConfigSelectGroupSchema,
|
||||
SessionConfigSelectOptionSchema,
|
||||
type AvailableCommand,
|
||||
type InitializeResponse,
|
||||
type SessionConfigOption,
|
||||
type SessionConfigSelectOption,
|
||||
type SessionModelState
|
||||
import type {
|
||||
AvailableCommand,
|
||||
InitializeResponse,
|
||||
SessionConfigOption,
|
||||
SessionModelState
|
||||
} from './generated/acp-protocol.generated'
|
||||
|
||||
type SelectOption = Extract<SessionConfigOption, { type: 'select' }>
|
||||
@@ -29,22 +27,6 @@ export type AcpOptionWrite =
|
||||
| { method: 'config'; configId: string; value: string }
|
||||
| { method: 'model'; modelId: string }
|
||||
|
||||
function selectChoices(option: SelectOption): SessionConfigSelectOption[] {
|
||||
const choices: SessionConfigSelectOption[] = []
|
||||
for (const entry of option.options) {
|
||||
const group = SessionConfigSelectGroupSchema.safeParse(entry)
|
||||
if (group.success) {
|
||||
choices.push(...group.data.options)
|
||||
continue
|
||||
}
|
||||
const choice = SessionConfigSelectOptionSchema.safeParse(entry)
|
||||
if (choice.success) {
|
||||
choices.push(choice.data)
|
||||
}
|
||||
}
|
||||
return choices
|
||||
}
|
||||
|
||||
function isSelect(option: SessionConfigOption): option is SelectOption {
|
||||
return option.type === 'select'
|
||||
}
|
||||
@@ -125,6 +107,20 @@ export class AcpStructuredOptions {
|
||||
}
|
||||
}
|
||||
|
||||
matchesNativeRestoredModel(value: string): boolean {
|
||||
if (
|
||||
this.resolvesConfig ||
|
||||
this.picked.has('model') ||
|
||||
(this.dialect.effortChangesModel && this.picked.has('effort'))
|
||||
) {
|
||||
return false
|
||||
}
|
||||
return (
|
||||
value.length > 0 &&
|
||||
(this.select('model')?.currentValue ?? this.models?.currentModelId) === value
|
||||
)
|
||||
}
|
||||
|
||||
notePick(key: string): void {
|
||||
this.picked.add(key)
|
||||
}
|
||||
@@ -202,7 +198,7 @@ export class AcpStructuredOptions {
|
||||
const modelOption = this.select('model')
|
||||
const effortOption = this.select('thought_level')
|
||||
const sessionEfforts: AgentSessionOptionChoice[] = effortOption
|
||||
? selectChoices(effortOption).map((choice) => ({
|
||||
? acpSelectChoices(effortOption).map((choice) => ({
|
||||
value: choice.value,
|
||||
label: choice.name,
|
||||
...(choice.description ? { description: choice.description } : {})
|
||||
@@ -210,7 +206,7 @@ export class AcpStructuredOptions {
|
||||
: []
|
||||
const currentModel = (modelOption?.currentValue ?? this.models?.currentModelId) || undefined
|
||||
const listed: { id: string; label: string; description?: string }[] = modelOption
|
||||
? selectChoices(modelOption).map((choice) => ({
|
||||
? acpSelectChoices(modelOption).map((choice) => ({
|
||||
id: choice.value,
|
||||
label: choice.name,
|
||||
...(choice.description ? { description: choice.description } : {})
|
||||
|
||||
@@ -0,0 +1,385 @@
|
||||
import { afterEach, expect, it } from 'vitest'
|
||||
import { closeProviderTimelineRigs } from '../native-chat/agent-session-timeline/provider-timeline-assembler-test-support'
|
||||
import { CALLER } from '../native-chat/agent-session-wire/structured-agent-session-host-test-harness'
|
||||
import {
|
||||
HOST_TEST_SESSION as SESSION,
|
||||
hostTestAttachParams
|
||||
} from '../native-chat/agent-session-wire/structured-agent-session-host-test-data'
|
||||
import { acpLaunchSpecFor } from './acp-launch-specs'
|
||||
import type { AcpScriptedAgent, FakeFrame } from './acp-scripted-agent.test-support'
|
||||
import { PROVIDER_SESSION, replyChunk, waitFor } from './acp-structured-adapter.test-support'
|
||||
import { framesOf, launch, openHostRig, send } from './acp-structured-host.test-support'
|
||||
import {
|
||||
SetSessionConfigOptionRequestSchema,
|
||||
type SessionConfigOption
|
||||
} from './generated/acp-protocol.generated'
|
||||
|
||||
// OpenCode 2.0.21 cold-load capture: the current model is absent from the partial inventory.
|
||||
const MODEL = 'existing_lb/gpt-6.1-sol'
|
||||
const OTHER = 'opencode/beam-free'
|
||||
const select = (id: string, category: string, currentValue: string): SessionConfigOption => ({
|
||||
id,
|
||||
name: id,
|
||||
category,
|
||||
type: 'select',
|
||||
currentValue,
|
||||
options: []
|
||||
})
|
||||
const config = (model = MODEL, modelId = 'model', effort?: string): SessionConfigOption[] => [
|
||||
select(modelId, 'model', model),
|
||||
...(effort ? [select('variant', 'thought_level', effort)] : []),
|
||||
select('mode', 'mode', 'default')
|
||||
]
|
||||
const push = (configOptions: SessionConfigOption[], sessionId = PROVIDER_SESSION): FakeFrame => ({
|
||||
jsonrpc: '2.0',
|
||||
method: 'session/update',
|
||||
params: { sessionId, update: { sessionUpdate: 'config_option_update', configOptions } }
|
||||
})
|
||||
const response = (frame: FakeFrame, configOptions: SessionConfigOption[]): FakeFrame => ({
|
||||
jsonrpc: '2.0',
|
||||
id: frame.id,
|
||||
result: { sessionId: PROVIDER_SESSION, configOptions }
|
||||
})
|
||||
const chunk = (agent: AcpScriptedAgent, frames: FakeFrame[]) =>
|
||||
agent.stdout.write(`${frames.map((frame) => JSON.stringify(frame)).join('\n')}\n`)
|
||||
|
||||
afterEach(closeProviderTimelineRigs)
|
||||
|
||||
async function openModel(
|
||||
settings: {
|
||||
restored?: boolean
|
||||
agent?: 'opencode2' | 'omp'
|
||||
intent?: Record<string, string>
|
||||
permission?: boolean
|
||||
script?: (agent: AcpScriptedAgent, native: { model: string; effort: string }) => void
|
||||
} = {}
|
||||
) {
|
||||
const base = acpLaunchSpecFor(settings.agent ?? 'opencode2')!
|
||||
const spec = settings.permission
|
||||
? {
|
||||
...base,
|
||||
permissionModeConfig: {
|
||||
values: { ask: 'default', 'accept-edits': 'auto_edit', 'full-access': 'yolo' }
|
||||
}
|
||||
}
|
||||
: base
|
||||
const native = { model: MODEL, effort: 'low' }
|
||||
let resumed = false
|
||||
const f = await openHostRig({
|
||||
spec,
|
||||
deps: { resolveLaunch: launch(() => resumed, spec) },
|
||||
script: (agent) => {
|
||||
for (const method of ['session/new', 'session/load', 'session/resume']) {
|
||||
agent.on(method, (frame) =>
|
||||
agent.reply(frame, {
|
||||
sessionId: PROVIDER_SESSION,
|
||||
configOptions: config()
|
||||
})
|
||||
)
|
||||
}
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
if (SetSessionConfigOptionRequestSchema.parse(frame.params).configId === 'mode') {
|
||||
agent.reply(frame, { configOptions: config() })
|
||||
} else {
|
||||
agent.fail(frame, -32602, 'Invalid params', `model not found: ${MODEL}`)
|
||||
}
|
||||
})
|
||||
agent.on('session/prompt', (frame) => {
|
||||
agent.notify('session/update', replyChunk('', `${native.model}:${native.effort}`))
|
||||
agent.reply(frame, { stopReason: 'end_turn' })
|
||||
})
|
||||
if (resumed || settings.restored === false) {
|
||||
settings.script?.(agent, native)
|
||||
}
|
||||
}
|
||||
})
|
||||
const attach = (fence: number | null) =>
|
||||
f.host.attach(
|
||||
CALLER,
|
||||
hostTestAttachParams(fence, {
|
||||
provider: spec.agent,
|
||||
agent: spec.agent,
|
||||
accountHome:
|
||||
spec.agent === 'omp'
|
||||
? { variable: 'PI_CODING_AGENT_DIR', path: '/acp-test' }
|
||||
: { kind: 'opencode', locator: { kind: 'unmanaged' } },
|
||||
providerHandle: undefined,
|
||||
options: settings.intent ?? { model: MODEL }
|
||||
})
|
||||
)
|
||||
expect(await attach(null)).toMatchObject({ ok: true })
|
||||
await f.ready()
|
||||
if (settings.restored !== false) {
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
resumed = true
|
||||
expect(await attach(f.fence())).toMatchObject({ ok: true })
|
||||
await f.ready()
|
||||
}
|
||||
const reply = async (text: string, expected: string) => {
|
||||
const id = await send(f.host, text)
|
||||
await waitFor(async () => {
|
||||
expect(
|
||||
(await f.host.journalSnapshot(SESSION)).submissions.find(
|
||||
(entry) => entry.clientMessageId === id
|
||||
)
|
||||
).toMatchObject({ dispatchState: 'accepted' })
|
||||
const messages = await f.messages()
|
||||
expect(
|
||||
messages,
|
||||
JSON.stringify({ messages, controls: framesOf(f.rig.child(), 'session/set_config_option') })
|
||||
).toContain(expected)
|
||||
expect(f.host.collaboratorsForTests().sessions.get(SESSION)!.journal.runningTurn()).toBeNull()
|
||||
})
|
||||
return id
|
||||
}
|
||||
return { ...f, native, reply }
|
||||
}
|
||||
|
||||
it.each(['opencode2', 'omp'] as const)(
|
||||
'resumes %s with its exact saved model outside the inventory for two replies',
|
||||
async (agent) => {
|
||||
const f = await openModel({ agent })
|
||||
await f.reply('first', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.reply('second', 'existing_lb/gpt-6.1-sol:low')
|
||||
expect(framesOf(f.rig.child(), 'session/prompt')).toHaveLength(2)
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['@role', '@role:high', 'retired'])(
|
||||
'preserves literal saved intent %j when the provider rejects it',
|
||||
async (model) => {
|
||||
const f = await openModel({ agent: 'omp', intent: { model } })
|
||||
const id = await send(f.host, 'literal choice')
|
||||
await waitFor(async () =>
|
||||
expect(
|
||||
(await f.host.journalSnapshot(SESSION)).submissions.find(
|
||||
(entry) => entry.clientMessageId === id
|
||||
)
|
||||
).toMatchObject({ dispatchState: 'rejected' })
|
||||
)
|
||||
expect(f.store.getRecord(SESSION)?.options?.model).toBe(model)
|
||||
expect(framesOf(f.rig.child(), 'session/prompt')).toHaveLength(0)
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['canonical', 'missing'] as const)(
|
||||
'retains successful literal alias proof with %s readback',
|
||||
async (echo) => {
|
||||
let applied = false
|
||||
const f = await openModel({
|
||||
intent: { model: 'alias' },
|
||||
script: (agent, native) => {
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
if (applied) {
|
||||
agent.fail(frame, -32602, 'Invalid params', 'alias cannot be resolved twice')
|
||||
return
|
||||
}
|
||||
expect(SetSessionConfigOptionRequestSchema.parse(frame.params).value).toBe('alias')
|
||||
applied = true
|
||||
native.model = 'resolved/provider-model'
|
||||
agent.reply(frame, { configOptions: echo === 'missing' ? [] : config(native.model) })
|
||||
})
|
||||
}
|
||||
})
|
||||
await f.reply('first', 'resolved/provider-model:low')
|
||||
await f.reply('second', 'resolved/provider-model:low')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
}
|
||||
)
|
||||
|
||||
it('writes explicit new-chat input even when its provisional report is equal', async () => {
|
||||
const f = await openModel({
|
||||
restored: false,
|
||||
script: (agent, native) => {
|
||||
native.model = 'provisional'
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
native.model = String(SetSessionConfigOptionRequestSchema.parse(frame.params).value)
|
||||
agent.reply(frame, { configOptions: config(native.model) })
|
||||
})
|
||||
}
|
||||
})
|
||||
await f.reply('explicit new chat', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
})
|
||||
|
||||
it.each(['missing', 'echoed'] as const)(
|
||||
'applies model before unproven explicit effort with %s descriptor',
|
||||
async (descriptor) => {
|
||||
const f = await openModel({
|
||||
intent: { model: MODEL, effort: 'high' },
|
||||
script: (agent, native) => {
|
||||
let modelSet = false
|
||||
if (descriptor === 'echoed') {
|
||||
agent.on('session/load', (frame) =>
|
||||
agent.reply(frame, { configOptions: config(MODEL, 'model', 'high') })
|
||||
)
|
||||
}
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
const { configId, value } = SetSessionConfigOptionRequestSchema.parse(frame.params)
|
||||
if (configId === 'model') {
|
||||
modelSet = true
|
||||
} else if (configId === 'variant' && modelSet) {
|
||||
native.effort = String(value)
|
||||
} else {
|
||||
agent.fail(frame, -32602, 'Invalid params', 'effort requires model activation')
|
||||
return
|
||||
}
|
||||
agent.reply(frame, { configOptions: config(MODEL, 'model', native.effort) })
|
||||
})
|
||||
}
|
||||
})
|
||||
await f.reply('use high', 'existing_lb/gpt-6.1-sol:high')
|
||||
await f.reply('keep high', 'existing_lb/gpt-6.1-sol:high')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
}
|
||||
)
|
||||
|
||||
it.each(['response-push', 'push-response'] as const)(
|
||||
'reduces restored %s records in one chunk before dispatch',
|
||||
async (order) => {
|
||||
const f = await openModel({
|
||||
script: (agent, native) => {
|
||||
agent.on('session/load', (frame) => {
|
||||
native.model = order === 'response-push' ? OTHER : MODEL
|
||||
const records = [response(frame, config()), push(config(OTHER))]
|
||||
chunk(agent, order === 'response-push' ? records : records.toReversed())
|
||||
})
|
||||
if (order === 'response-push') {
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
native.model = String(SetSessionConfigOptionRequestSchema.parse(frame.params).value)
|
||||
agent.reply(frame, { configOptions: config(native.model) })
|
||||
})
|
||||
}
|
||||
}
|
||||
})
|
||||
await f.reply('honor saved model', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
}
|
||||
)
|
||||
|
||||
it('flushes fresh early updates before the response and keeps the later descriptor', async () => {
|
||||
const f = await openModel({
|
||||
restored: false,
|
||||
script: (agent, native) => {
|
||||
agent.on('session/new', (frame) =>
|
||||
chunk(agent, [
|
||||
push(config(OTHER, 'early-model')),
|
||||
response(frame, config(MODEL, 'response-model')),
|
||||
push(config(OTHER, 'latest-model'))
|
||||
])
|
||||
)
|
||||
native.model = OTHER
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
const { configId, value } = SetSessionConfigOptionRequestSchema.parse(frame.params)
|
||||
if (configId !== 'latest-model') {
|
||||
agent.fail(frame, -32602, 'Invalid params', 'obsolete model descriptor')
|
||||
return
|
||||
}
|
||||
native.model = String(value)
|
||||
agent.reply(frame, { configOptions: config(native.model, 'latest-model') })
|
||||
})
|
||||
}
|
||||
})
|
||||
await f.reply('explicit model on new chat', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
})
|
||||
|
||||
it.each(['response-push', 'push-response'] as const)(
|
||||
'orders permission %s without replaying the load snapshot',
|
||||
async (order) => {
|
||||
const f = await openModel({
|
||||
permission: true,
|
||||
script: (agent, native) => {
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
const { configId, value } = SetSessionConfigOptionRequestSchema.parse(frame.params)
|
||||
if (configId === 'mode') {
|
||||
native.model = order === 'response-push' ? OTHER : MODEL
|
||||
const records = [response(frame, config()), push(config(OTHER))]
|
||||
chunk(agent, order === 'response-push' ? records : records.toReversed())
|
||||
} else {
|
||||
if (native.model === MODEL) {
|
||||
agent.fail(frame, -32602, 'Invalid params', 'redundant model control refused')
|
||||
return
|
||||
}
|
||||
native.model = String(value)
|
||||
agent.reply(frame, { configOptions: config(native.model) })
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
await f.reply('after permission setup', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
}
|
||||
)
|
||||
|
||||
it('does not adopt another session model update into the selected restored chat', async () => {
|
||||
const f = await openModel()
|
||||
f.rig.child().agent.notify('session/update', push(config(OTHER), 'old-session').params)
|
||||
await f.reply('same saved chat', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
})
|
||||
|
||||
it('retains the native legacy model without requiring inventory membership', async () => {
|
||||
const f = await openModel({
|
||||
agent: 'omp',
|
||||
script: (agent) => {
|
||||
agent.on('session/load', (frame) =>
|
||||
agent.reply(frame, {
|
||||
models: { currentModelId: MODEL, availableModels: [] }
|
||||
})
|
||||
)
|
||||
agent.on('session/set_model', (frame) =>
|
||||
agent.fail(frame, -32602, 'Invalid params', 'model not found')
|
||||
)
|
||||
}
|
||||
})
|
||||
await f.reply('legacy model', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
})
|
||||
|
||||
it('reconciles live native drift before sending with the saved choice', async () => {
|
||||
const f = await openModel({
|
||||
script: (agent, native) => {
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
native.model = String(SetSessionConfigOptionRequestSchema.parse(frame.params).value)
|
||||
agent.reply(frame, { configOptions: config(native.model) })
|
||||
})
|
||||
}
|
||||
})
|
||||
await f.reply('before drift', 'existing_lb/gpt-6.1-sol:low')
|
||||
f.native.model = OTHER
|
||||
f.rig.child().agent.notify('session/update', push(config(OTHER)).params)
|
||||
await f.reply('after drift', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
})
|
||||
|
||||
it('does not regain native model adoption after model-changing effort with a stale echo', async () => {
|
||||
const f = await openModel({
|
||||
script: (agent, native) => {
|
||||
agent.on('session/load', (frame) =>
|
||||
agent.reply(frame, { configOptions: config(MODEL, 'model', 'low') })
|
||||
)
|
||||
agent.on('session/set_config_option', (frame) => {
|
||||
const { configId, value } = SetSessionConfigOptionRequestSchema.parse(frame.params)
|
||||
if (configId === 'variant') {
|
||||
native.effort = String(value)
|
||||
native.model = OTHER
|
||||
} else {
|
||||
native.model = String(value)
|
||||
}
|
||||
agent.reply(frame, { configOptions: config(MODEL, 'model', native.effort) })
|
||||
})
|
||||
}
|
||||
})
|
||||
await f.reply('before effort', 'existing_lb/gpt-6.1-sol:low')
|
||||
await f.rig.adapter.setOption({
|
||||
sessionId: SESSION,
|
||||
fence: f.fence(),
|
||||
key: 'effort',
|
||||
value: 'high'
|
||||
})
|
||||
await f.reply('after effort changed the composite model', 'existing_lb/gpt-6.1-sol:high')
|
||||
await f.host.close(SESSION, 'user-close')
|
||||
})
|
||||
@@ -55,7 +55,10 @@ export function routeAcpSessionEvent(
|
||||
at: number,
|
||||
reattaching = false
|
||||
): void {
|
||||
if (event.kind === 'known') {
|
||||
if (
|
||||
event.kind === 'known' &&
|
||||
event.notification.sessionId === session.lane.translator.providerSessionId
|
||||
) {
|
||||
const { update } = event.notification
|
||||
if (update.sessionUpdate === 'available_commands_update') {
|
||||
session.options.adoptCommands(update.availableCommands)
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
import { mkdirSync, mkdtempSync, rmSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { PassThrough } from 'node:stream'
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
import { createFakePipedChild } from '../../shared/__fixtures__/fake-spawned-child'
|
||||
import { AcpScriptedAgent } from '../acp/acp-scripted-agent.test-support'
|
||||
import { acpLaunchSpecFor } from '../acp/acp-launch-specs'
|
||||
import { openAcpAdapterRig, sendHello } from '../acp/acp-structured-adapter.test-support'
|
||||
import {
|
||||
closeProviderTimelineRigs,
|
||||
messageText,
|
||||
SESSION
|
||||
} from '../native-chat/agent-session-timeline/provider-timeline-assembler-test-support'
|
||||
import { readOpenCodePromptFailure } from '../foreign-sqlite-readers/readers/opencode-prompt-failure'
|
||||
import type { OpenCodePromptFailureQuery } from '../foreign-sqlite-readers/opencode-prompt-failure-result'
|
||||
import SyncDatabase from '../sqlite/sync-database'
|
||||
import { createOpenCodeAcpConnection } from './opencode-acp-connection'
|
||||
|
||||
const NOW = 1_800_000_000_000
|
||||
const cleanups: (() => Promise<void>)[] = []
|
||||
afterEach(async () => {
|
||||
for (const cleanup of cleanups.splice(0)) {
|
||||
await cleanup()
|
||||
}
|
||||
vi.unstubAllEnvs()
|
||||
vi.restoreAllMocks()
|
||||
await closeProviderTimelineRigs()
|
||||
})
|
||||
|
||||
async function fixture(
|
||||
native: unknown,
|
||||
options: {
|
||||
stale?: boolean
|
||||
start?: boolean
|
||||
unavailable?: boolean
|
||||
readGate?: Promise<void>
|
||||
readStarted?: () => void
|
||||
acpCode?: number
|
||||
} = {}
|
||||
) {
|
||||
const directory = mkdtempSync(join(tmpdir(), 'orca-opencode-acp-failure-'))
|
||||
const dataHome = join(directory, 'account-data')
|
||||
mkdirSync(join(dataHome, 'opencode'), { recursive: true })
|
||||
const dbPath = join(dataHome, 'opencode', 'opencode.db')
|
||||
const db = new SyncDatabase(dbPath)
|
||||
db.exec(`CREATE TABLE session_message (
|
||||
id TEXT PRIMARY KEY, session_id TEXT, type TEXT, seq INTEGER, time_created INTEGER, data TEXT
|
||||
)`)
|
||||
const agent = new AcpScriptedAgent()
|
||||
const child = Object.assign(createFakePipedChild(), {
|
||||
pid: 9_999_999,
|
||||
stdout: agent.stdout,
|
||||
stdin: agent.stdin,
|
||||
stderr: new PassThrough()
|
||||
})
|
||||
agent.on('initialize', (frame) => agent.reply(frame, { protocolVersion: 1 }))
|
||||
agent.on('session/new', (frame) => agent.reply(frame, { sessionId: 'ses-own' }))
|
||||
let turn = 0
|
||||
agent.on('session/prompt', (frame) => {
|
||||
turn++
|
||||
db.prepare('INSERT OR REPLACE INTO session_message VALUES (?, ?, ?, ?, ?, ?)').run(
|
||||
`input-${turn}`,
|
||||
'ses-own',
|
||||
'user',
|
||||
turn * 10,
|
||||
NOW,
|
||||
'{}'
|
||||
)
|
||||
db.prepare('INSERT OR REPLACE INTO session_message VALUES (?, ?, ?, ?, ?, ?)').run(
|
||||
`outcome-${turn}`,
|
||||
'ses-own',
|
||||
'idle',
|
||||
turn * 10 + 1,
|
||||
options.stale ? 1 : NOW,
|
||||
JSON.stringify({ error: native })
|
||||
)
|
||||
agent.fail(
|
||||
frame,
|
||||
options.acpCode ?? -32000,
|
||||
'Authentication required: provider authentication required',
|
||||
{
|
||||
details: 'provider authentication required'
|
||||
}
|
||||
)
|
||||
})
|
||||
const readFailure = vi.fn(async (query: OpenCodePromptFailureQuery) => {
|
||||
if (options.unavailable) {
|
||||
throw new Error('database unavailable')
|
||||
}
|
||||
const result = readOpenCodePromptFailure(query)
|
||||
options.readStarted?.()
|
||||
await options.readGate
|
||||
return result
|
||||
})
|
||||
const connection = createOpenCodeAcpConnection(
|
||||
{
|
||||
command: 'opencode2',
|
||||
args: ['acp'],
|
||||
cwd: directory,
|
||||
env: { XDG_DATA_HOME: dataHome },
|
||||
envToDelete: ['OPENCODE_DB']
|
||||
},
|
||||
{},
|
||||
() => child,
|
||||
readFailure
|
||||
)
|
||||
cleanups.push(async () => {
|
||||
child.emit('exit', 0, null)
|
||||
await connection.close()
|
||||
db.close()
|
||||
rmSync(directory, { recursive: true, force: true })
|
||||
})
|
||||
if (options.start !== false) {
|
||||
await connection.start({ cwd: directory, mcpServers: [] })
|
||||
}
|
||||
return { connection, readFailure, dbPath, agent, child, cwd: directory }
|
||||
}
|
||||
|
||||
const quota = { type: 'provider.quota', message: 'Free usage limit reached.', status: 429 }
|
||||
|
||||
describe('OpenCode ACP native failure recovery', () => {
|
||||
it('journals the recovered failure through the full chat adapter and accepts the next send', async () => {
|
||||
vi.spyOn(Date, 'now').mockReturnValue(NOW)
|
||||
const spec = acpLaunchSpecFor('opencode2')
|
||||
if (!spec) {
|
||||
throw new Error('OpenCode 2 launch specification missing')
|
||||
}
|
||||
const { connection, agent, cwd } = await fixture(
|
||||
{ ...quota, retryAfterMs: 60_000 },
|
||||
{ start: false }
|
||||
)
|
||||
const rig = await openAcpAdapterRig({
|
||||
spec,
|
||||
launch: { cwd },
|
||||
deps: { connect: () => connection, now: Date.now }
|
||||
})
|
||||
cleanups.push(async () => {
|
||||
await rig.adapter.closeSession(SESSION)
|
||||
})
|
||||
await rig.acquire()
|
||||
await sendHello(rig, 'first')
|
||||
await rig.settle()
|
||||
expect((await rig.rig.rows()).map((row) => row.body)).toContainEqual(
|
||||
expect.objectContaining({
|
||||
kind: 'status',
|
||||
tone: 'warning',
|
||||
failure: expect.objectContaining({
|
||||
kind: 'usageLimitReached',
|
||||
detail: { text: quota.message, audience: 'person' },
|
||||
usageLimit: { resetsAt: expect.any(Number) }
|
||||
})
|
||||
})
|
||||
)
|
||||
expect((await rig.rig.turns())[0]?.outcome).toBe('failure')
|
||||
agent.on('session/prompt', (frame) => {
|
||||
agent.notify('session/update', {
|
||||
sessionId: 'ses-own',
|
||||
update: {
|
||||
sessionUpdate: 'agent_message_chunk',
|
||||
content: { type: 'text', text: 'reply after failure' }
|
||||
}
|
||||
})
|
||||
agent.reply(frame, { stopReason: 'end_turn' })
|
||||
})
|
||||
await sendHello(rig, 'second')
|
||||
await rig.settle()
|
||||
expect((await rig.rig.turns()).map((turn) => turn.outcome)).toEqual(['failure', 'success'])
|
||||
expect((await rig.rig.rows()).map((row) => messageText(row.body))).toContain(
|
||||
'reply after failure'
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -5,7 +5,7 @@ import type { PipedProcessSpawner } from '@orca/process-host/process-spec'
|
||||
import { isRecord } from '../../shared/agent-status/child-work/agent-status-child-work-value-guards'
|
||||
import { AcpAgentConnection, type AcpAgentConnectionOptions } from '../acp/acp-agent-connection'
|
||||
import { AcpAgentError, AcpAuthRequiredError, AcpSignInPromptError } from '../acp/acp-errors'
|
||||
import type { AcpSessionStartOptions } from '../acp/acp-session-setup'
|
||||
import type { AcpSessionStarted, AcpSessionStartOptions } from '../acp/acp-session-setup'
|
||||
import type { PromptRequest } from '../acp/generated/acp-protocol.generated'
|
||||
import { readOpenCodePromptFailure } from '../foreign-sqlite-readers/foreign-sqlite-reader-spawn'
|
||||
import type { OpenCodePromptFailure } from '../foreign-sqlite-readers/opencode-prompt-failure-result'
|
||||
@@ -70,8 +70,11 @@ class OpenCodeAcpConnection extends AcpAgentConnection {
|
||||
this.dbPath = dbPath
|
||||
}
|
||||
|
||||
override async start(options: AcpSessionStartOptions) {
|
||||
const started = await super.start(options)
|
||||
override async start(
|
||||
options: AcpSessionStartOptions,
|
||||
received?: (started: AcpSessionStarted) => void
|
||||
) {
|
||||
const started = await super.start(options, received)
|
||||
this.providerSessionId = started.sessionId
|
||||
return started
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user