diff --git a/src/sidechat-core.ts b/src/sidechat-core.ts index 984602c7..2a97bb86 100644 --- a/src/sidechat-core.ts +++ b/src/sidechat-core.ts @@ -610,3 +610,86 @@ export function resolvePresetId( } return header.agentPreset } + +/** One model route as the durable log records it (the shape of a + * `model/selection` event payload and of the core `modelSelection` + * projection rows). */ +export interface SidechatModelSelection { + provider: string + model: string + reasoningEffort?: string +} + +/** + * The model selection a session CURRENTLY runs, projected from its durable + * log (mirror of the core `modelSelection` projection — replicated here + * like resolvePresetId to avoid a host dependency). An explicit + * `model/selection` event stays PENDING until a same-route `request/header` + * consumes it; the value the composer's model selector shows is + * `pending ?? lastUsed`. + * + * This is NOT what `agent.options.provider/model` holds: those freeze the + * creation-time deployment default and are never rewritten by a UI model + * switch — DSH 0.1.5 routes requests through the session-local selection + * and its `agent/request` waterfall instead. Anyone inheriting "the + * parent's current model" must read this projection; inheriting + * `parent.options` verbatim silently ships the stale creation default + * (issue #368). + * + * A `request/header` contributes provider/model/effort, EXCEPT when its + * effort is marked as an adapter default (`adapterDefaults.reasoningEffort`) + * which the core selection getter deliberately does not adopt as a sticky pick. + */ +export function parentModelSelection( + events: readonly SidechatLogEvent[], +): SidechatModelSelection | undefined { + let pending: SidechatModelSelection | undefined + let lastUsed: SidechatModelSelection | undefined + for (const event of events) { + if (event.type === 'model/selection') { + const selection = looseSelection(dataOf(event)) + if (selection !== undefined) pending = selection + continue + } + if (event.type !== 'request/header') continue + const header = (dataOf(event).header as { + config?: unknown + adapterDefaults?: { reasoningEffort?: boolean } + } | undefined) + const config = header?.config + if (config === null || typeof config !== 'object') continue + const selection = looseSelection(config as Record) + if (selection === undefined) continue + const isDefaultEffort = header?.adapterDefaults?.reasoningEffort === true + lastUsed = { + provider: selection.provider, + model: selection.model, + ...(!isDefaultEffort && selection.reasoningEffort !== undefined ? { reasoningEffort: selection.reasoningEffort } : {}), + } + if (sameSelection(pending, lastUsed)) pending = undefined + } + return pending ?? lastUsed +} + +function sameSelection( + left: SidechatModelSelection | undefined, + right: SidechatModelSelection | undefined, +): boolean { + if (left === right) return true + if (left === undefined || right === undefined) return false + return left.provider === right.provider + && left.model === right.model + && left.reasoningEffort === right.reasoningEffort +} + +/** Narrow one loose record into a model selection (non-empty strings only). */ +function looseSelection(data: Record): SidechatModelSelection | undefined { + const { provider, model, reasoningEffort } = data + if (typeof provider !== 'string' || provider === '') return undefined + if (typeof model !== 'string' || model === '') return undefined + return { + provider, + model, + ...(typeof reasoningEffort === 'string' && reasoningEffort !== '' ? { reasoningEffort } : {}), + } +} diff --git a/src/sidechat-routes.ts b/src/sidechat-routes.ts index 68ceca0f..8285520a 100644 --- a/src/sidechat-routes.ts +++ b/src/sidechat-routes.ts @@ -22,7 +22,7 @@ * AgentRegistry.resume, composing the preset the child recorded. */ import { randomUUID } from 'node:crypto' -import { createUserMessage, type ContentBlock, type UserMessage } from '@deepseek-ai/dsh-llm' +import { createUserMessage, ReasoningEffortId, type ContentBlock, type UserMessage } from '@deepseek-ai/dsh-llm' import type { Agent, AgentSetup, CreateAgentOptions, ResumeAgentOptions } from '@deepseek-ai/dsh-agent' import { snapshotSubagentDescriptor } from '@deepseek-ai/dsh-subagent' import type { Context as CordisContext } from '@deepseek-ai/cordis' @@ -38,6 +38,7 @@ import { boundaryDelivered, buildSidechatInheritance, liveEventsOf, + parentModelSelection, resolvePresetId, SIDE_BOUNDARY_PROMPT, SIDE_INJECTION_SOURCE_KIND, @@ -238,6 +239,19 @@ export function buildSidechatApi(ctx: Context, live?: AssistantLiveBuffer): Side throw new SidebarError('sidechat-error', `parent session "${sessionId}" is not running`, 409) } const parentSession = parent.session + // The parent's CURRENT model route. agent.options freezes the + // creation-time deployment default — a composer model switch rides + // `model/selection` events + the session-local selection and never + // rewrites options — so the child inherits the durable projection + // (falling back to the options snapshot only when the log carries no + // selection at all). Inheriting parent.options verbatim silently + // shipped the stale default instead of the model the user sees + // selected in the parent composer (#368). + const parentSelection = parentModelSelection( + parentSession.snapshotEvents() as unknown as readonly SidechatLogEvent[], + ) + const routeProvider = parentSelection?.provider ?? parent.options.provider + const routeModel = parentSelection?.model ?? parent.options.model const inheritance = buildSidechatInheritance( parentSession.snapshotEvents() as unknown as readonly SidechatLogEvent[], live?.chunksFor(sessionId) ?? [], @@ -257,8 +271,8 @@ export function buildSidechatApi(ctx: Context, live?: AssistantLiveBuffer): Side mode: 'continuable', provider: 'sidechat', label, - ...(parent.options.provider === undefined ? {} : { agentProvider: parent.options.provider }), - ...(parent.options.model === undefined ? {} : { agentModel: parent.options.model }), + ...(routeProvider === undefined ? {} : { agentProvider: routeProvider }), + ...(routeModel === undefined ? {} : { agentModel: routeModel }), }) const descriptorEvent: SeedEvent = { type: 'subagent/descriptor', @@ -277,6 +291,19 @@ export function buildSidechatApi(ctx: Context, live?: AssistantLiveBuffer): Side // would then claim and send that stale message BEFORE the boundary + // question. The marker keeps `ownEvents()` at the end-seed boundary, so // the inherited inbox replays to empty. + const targetEffort = parentSelection !== undefined + ? (parentSelection.reasoningEffort === undefined ? undefined : ReasoningEffortId(parentSelection.reasoningEffort)) + : parent.options.reasoningEffort + const childAgentOptions: CreateAgentOptions['agentOptions'] = { + ...parent.options, + ...(routeProvider === undefined ? {} : { provider: routeProvider }), + ...(routeModel === undefined ? {} : { model: routeModel }), + } + if (targetEffort !== undefined) { + childAgentOptions.reasoningEffort = targetEffort + } else { + delete childAgentOptions.reasoningEffort + } const options: CreateAgentOptions = { sessionId: childId, meta: { @@ -289,7 +316,7 @@ export function buildSidechatApi(ctx: Context, live?: AssistantLiveBuffer): Side }, seed: seed as unknown as readonly SessionEvent[], inheritedEventCount: SessionLogOffset(seed.length), - agentOptions: { ...parent.options }, + agentOptions: childAgentOptions, setup, signal: AbortSignal.timeout(CREATE_TIMEOUT_MS), } diff --git a/tests/sidechat-core.spec.ts b/tests/sidechat-core.spec.ts index 508ba6f9..ac6952ec 100644 --- a/tests/sidechat-core.spec.ts +++ b/tests/sidechat-core.spec.ts @@ -15,6 +15,7 @@ import { buildSidechatInheritance, hasDanglingToolCall, isContextInjectionMessage, + parentModelSelection, resolvePresetId, sideLabel, sideThreadRows, @@ -432,3 +433,71 @@ describe('isContextInjectionMessage', () => { expect(isContextInjectionMessage({ content: [{ type: 'text', text: 'no source row' }] })).toBe(false) }) }) + +describe('parentModelSelection', () => { + it('returns undefined for a log without selection state', () => { + expect(parentModelSelection([])).toBeUndefined() + expect(parentModelSelection([ + ev('user/message', 0, { content: [{ type: 'text', text: 'q' }], source: { kind: 'user' } }), + ev('turn/start', 1, { turn: 1 }), + ])).toBeUndefined() + }) + + it('adopts an explicit pending selection with its effort', () => { + // The composer switch logged after the last request: nothing consumed it + // yet, so it IS the current selection (the view the selector shows). + expect(parentModelSelection([ + ev('request/header', 0, { header: { config: { provider: 'p1', model: 'm1' } } }), + ev('model/selection', 1, { provider: 'p2', model: 'm2', reasoningEffort: 'high' }), + ])).toEqual({ provider: 'p2', model: 'm2', reasoningEffort: 'high' }) + }) + + it('lets a same-route request header consume the pending selection preserving explicit effort', () => { + // Consumed pending -> the header's route is current (effort preserved when not an adapter default). + expect(parentModelSelection([ + ev('model/selection', 0, { provider: 'p2', model: 'm2', reasoningEffort: 'high' }), + ev('request/header', 1, { header: { config: { provider: 'p2', model: 'm2', reasoningEffort: 'high' } } }), + ])).toEqual({ provider: 'p2', model: 'm2', reasoningEffort: 'high' }) + }) + + it('drops adapter-default effort from request headers', () => { + expect(parentModelSelection([ + ev('request/header', 0, { + header: { + config: { provider: 'p1', model: 'm1', reasoningEffort: 'low' }, + adapterDefaults: { reasoningEffort: true }, + }, + }), + ])).toEqual({ provider: 'p1', model: 'm1' }) + }) + + it('keeps a pending selection a different-route header cannot consume', () => { + expect(parentModelSelection([ + ev('model/selection', 0, { provider: 'p2', model: 'm2' }), + ev('request/header', 1, { header: { config: { provider: 'p1', model: 'm1' } } }), + ])).toEqual({ provider: 'p2', model: 'm2' }) + }) + + it('falls back to the last request header when no explicit selection is pending', () => { + expect(parentModelSelection([ + ev('request/header', 0, { header: { config: { provider: 'p1', model: 'm1', reasoningEffort: 'low' } } }), + ev('request/header', 1, { header: { config: { provider: 'p1', model: 'm1' } } }), + ])).toEqual({ provider: 'p1', model: 'm1' }) + }) + + it('preserves non-default effort on request header fallback', () => { + expect(parentModelSelection([ + ev('request/header', 0, { header: { config: { provider: 'p1', model: 'm1', reasoningEffort: 'high' } } }), + ])).toEqual({ provider: 'p1', model: 'm1', reasoningEffort: 'high' }) + }) + + it('ignores malformed selection and header rows instead of throwing', () => { + expect(parentModelSelection([ + ev('model/selection', 0, { provider: '', model: 'm2' }), + ev('model/selection', 1, { provider: 'p2' }), + ev('request/header', 2, { header: { config: 'garbage' } }), + ev('request/header', 3, {}), + ev('model/selection', 4, { provider: 'p3', model: 'm3' }), + ])).toEqual({ provider: 'p3', model: 'm3' }) + }) +}) diff --git a/tests/sidechat-routes.spec.ts b/tests/sidechat-routes.spec.ts index 8f672fe5..2a9346c4 100644 --- a/tests/sidechat-routes.spec.ts +++ b/tests/sidechat-routes.spec.ts @@ -15,11 +15,15 @@ import { SIDE_BOUNDARY_PROMPT, SIDE_INJECTION_SOURCE_KIND, SIDE_NEW_THREAD_TITLE import type { Context } from '../src/context-types.ts' /** A fake live agent (inject/followup/cancel/inbox.clear spied). */ -function agent(id: string, over: { events?: unknown[]; header?: Record; provider?: string; model?: string } = {}) { +function agent(id: string, over: { events?: unknown[]; header?: Record; provider?: string; model?: string; reasoningEffort?: string } = {}) { return { id, status: 'idle' as const, - options: { provider: over.provider ?? 'test', model: over.model ?? 'model-x' }, + options: { + provider: over.provider ?? 'test', + model: over.model ?? 'model-x', + ...(over.reasoningEffort !== undefined ? { reasoningEffort: over.reasoningEffort } : {}), + }, session: { id, header: { cwd: '/p', delegationDepth: 0, agentPreset: 'preset-a', ...over.header }, @@ -286,6 +290,133 @@ describe('sidechat.start', () => { expect(services.rename).toHaveBeenCalledWith(child.session, sideLabel('explain the event flow')) }) + it('inherits the parent CURRENT model selection, not the stale options snapshot', async () => { + const parent = agent('parent', { + provider: 'ark-code', + model: 'glm-5.3-flash', // the creation-time deployment default (agent.options) + events: [ + ev('request/header', 0, { header: { config: { provider: 'ark-code', model: 'glm-5.3-flash' } } }), + // A composer switch NEVER rewrites agent.options — it appends this + // durable event and the session-local selection routes requests. + // The child must inherit the model the parent's composer shows, not + // the frozen creation default (issue #368: side threads silently + // ran the deployment default after an explicit parent switch). + ev('model/selection', 1, { provider: 'openrouter', model: 'ox-alpha', reasoningEffort: 'high' }), + ], + }) + const child = agent('child') + const services = happyServices(parent, child) + const api = buildSidechatApi(ctxWith(services)) + + await api['sidechat.start']({ sessionId: 'parent', question: 'side question' }) + + const options = services.create.mock.calls[0]![0] as { + agentOptions: Record + seed: readonly { type: string; data: Record }[] + } + expect(options.agentOptions).toEqual({ provider: 'openrouter', model: 'ox-alpha', reasoningEffort: 'high' }) + // The durable descriptor keeps the same route (honest catalog row). + expect(options.seed.at(-1)?.data).toMatchObject({ + agentProvider: 'openrouter', + agentModel: 'ox-alpha', + }) + }) + + it('inherits the parent last-used route from its request headers when no explicit switch is pending', async () => { + const parent = agent('parent', { + // agent.options still holds the creation default... + provider: 'ark-code', + model: 'glm-5.3-flash', + events: [ + // ...but the session has been running on another route since. + ev('request/header', 0, { header: { config: { provider: 'gemini', model: 'gemini-3.7-flash-high' } } }), + ], + }) + const child = agent('child') + const services = happyServices(parent, child) + const api = buildSidechatApi(ctxWith(services)) + + await api['sidechat.start']({ sessionId: 'parent', question: 'side question' }) + + const options = services.create.mock.calls[0]![0] as { agentOptions: Record } + expect(options.agentOptions).toEqual({ provider: 'gemini', model: 'gemini-3.7-flash-high' }) + }) + + it('inherits reasoningEffort from request headers when not marked as adapter default', async () => { + const parent = agent('parent', { + provider: 'ark-code', + model: 'glm-5.3-flash', + events: [ + ev('request/header', 0, { + header: { + config: { provider: 'openrouter', model: 'ox-alpha', reasoningEffort: 'high' }, + }, + }), + ], + }) + const child = agent('child') + const services = happyServices(parent, child) + const api = buildSidechatApi(ctxWith(services)) + + await api['sidechat.start']({ sessionId: 'parent', question: 'side question' }) + + const options = services.create.mock.calls[0]![0] as { agentOptions: Record } + expect(options.agentOptions).toEqual({ + provider: 'openrouter', + model: 'ox-alpha', + reasoningEffort: 'high', + }) + }) + + it('drops adapter-default reasoningEffort from request headers', async () => { + const parent = agent('parent', { + provider: 'ark-code', + model: 'glm-5.3-flash', + events: [ + ev('request/header', 0, { + header: { + config: { provider: 'openrouter', model: 'ox-alpha', reasoningEffort: 'low' }, + adapterDefaults: { reasoningEffort: true }, + }, + }), + ], + }) + const child = agent('child') + const services = happyServices(parent, child) + const api = buildSidechatApi(ctxWith(services)) + + await api['sidechat.start']({ sessionId: 'parent', question: 'side question' }) + + const options = services.create.mock.calls[0]![0] as { agentOptions: Record } + expect(options.agentOptions).toEqual({ + provider: 'openrouter', + model: 'ox-alpha', + }) + }) + + it('clears stale parent options reasoningEffort when parent switches to a model without effort', async () => { + const parent = agent('parent', { + provider: 'oai', + model: 'o1', + reasoningEffort: 'high', + events: [ + ev('model/selection', 0, { provider: 'ark-code', model: 'glm-5.3-flash' }), + ], + }) + const child = agent('child') + const services = happyServices(parent, child) + const api = buildSidechatApi(ctxWith(services)) + + await api['sidechat.start']({ sessionId: 'parent', question: 'side question' }) + + const options = services.create.mock.calls[0]![0] as { agentOptions: Record } + expect(options.agentOptions).toEqual({ + provider: 'ark-code', + model: 'glm-5.3-flash', + }) + expect(options.agentOptions.reasoningEffort).toBeUndefined() + }) + it('rejects a non-running parent', async () => { const parent = agent('parent', { events: [] }) const child = agent('child')