diff --git a/backend/src/index.ts b/backend/src/index.ts index cb0675a4..b674d485 100644 --- a/backend/src/index.ts +++ b/backend/src/index.ts @@ -272,7 +272,7 @@ const sessionGoalService = new SessionGoalService(db, openCodeClient, sessionSet sessionGoalService.loadOpenGoals() const multiRunService = new MultiRunService(db, openCodeClient, repoWorkspaces, sessionPermissionModeService) -const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient) +const changeWalkthroughService = new ChangeWalkthroughService(db, openCodeClient, sessionSettingsService) sseAggregator.onEvent((directory, event) => { sessionPermissionModeService.handleEvent(directory, event).catch((err) => { diff --git a/backend/src/services/change-walkthroughs.ts b/backend/src/services/change-walkthroughs.ts index 471ce7da..b291d016 100644 --- a/backend/src/services/change-walkthroughs.ts +++ b/backend/src/services/change-walkthroughs.ts @@ -4,6 +4,7 @@ import { z } from 'zod' import { formatOpenCodeModelRef, isSessionNotFoundError, + parseOpenCodeModelRef, type FileDiffInfo, type ModelRef, type SessionInfo, @@ -34,6 +35,7 @@ import { logger } from '../utils/logger' import { GenerateTextTimeoutError, generateTextWithTimeout } from './opencode/generate-text' import type { OpenCodeClient } from './opencode/client' import { readSessionChanges } from './session-changes' +import type { SettingsService } from './settings' import type { SSEEvent } from './sse-aggregator' const DEFAULT_TIMEOUT_MS = 120_000 @@ -614,6 +616,7 @@ export class ChangeWalkthroughService { constructor( private readonly db: Database, private readonly openCodeClient: OpenCodeClient, + private readonly settingsService: SettingsService, options: ChangeWalkthroughServiceOptions = {}, ) { this.timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS @@ -759,8 +762,9 @@ export class ChangeWalkthroughService { const previous = getChangeWalkthrough(this.db, sessionId) const title = session.title ?? sessionId - const modelKey = computeModelKey(session.model) - const storedModel = session.model ? formatOpenCodeModelRef(session.model) : null + const model = this.resolveWalkthroughModel(session) + const modelKey = computeModelKey(model) + const storedModel = model ? formatOpenCodeModelRef(model) : null if (previous && previous.diffHash === diffHash && !request.regenerate) { if (previous.stops.every((stop) => stop.status === 'ready')) { @@ -769,7 +773,7 @@ export class ChangeWalkthroughService { const unfinished = previous.stops.filter((stop) => stop.status !== 'ready') const resumed = await this.explainStops( - session, + model, title, previous.summary, unfinished, @@ -824,7 +828,7 @@ export class ChangeWalkthroughService { const prompt = buildWalkthroughPrompt({ title, hunks }) onModelStart() - const parsed = await this.callModelParsed(prompt, session.model, (text) => + const parsed = await this.callModelParsed(prompt, model, (text) => parseWalkthroughResponse(text, hunks), ) @@ -883,7 +887,7 @@ export class ChangeWalkthroughService { const planPrompt = buildWalkthroughPlanPrompt({ title, outline: outline.outline, previousStops }) onModelStart() - const planned = await this.callModelParsed(planPrompt, session.model, (text) => + const planned = await this.callModelParsed(planPrompt, model, (text) => parseWalkthroughPlan(text, outline.hunks), ) @@ -906,7 +910,7 @@ export class ChangeWalkthroughService { const pending = stops.filter((stop) => stop.status !== 'ready') if (pending.length > 0) { walkthrough = await this.explainStops( - session, + model, title, planned.summary, pending, @@ -924,7 +928,7 @@ export class ChangeWalkthroughService { } private async explainStops( - session: SessionInfo, + model: ModelRef | undefined, title: string, summary: string, stops: WalkthroughStop[], @@ -932,7 +936,7 @@ export class ChangeWalkthroughService { walkthrough: ChangeWalkthrough, onModelStart: () => void, ): Promise { - const modelKey = computeModelKey(session.model) + const modelKey = computeModelKey(model) let current = walkthrough await mapWithConcurrency(stops, WALKTHROUGH_EXPLAIN_CONCURRENCY, async (stop) => { @@ -941,7 +945,7 @@ export class ChangeWalkthroughService { let explained: WalkthroughStop try { - const explanation = await this.callModelParsed(explainPrompt, session.model, parseWalkthroughExplanation) + const explanation = await this.callModelParsed(explainPrompt, model, parseWalkthroughExplanation) explained = { ...stop, explanation, @@ -1022,4 +1026,10 @@ export class ChangeWalkthroughService { throw new ChangeWalkthroughError(getErrorMessage(error) || 'Failed to read session', 502) } } + + private resolveWalkthroughModel(session: SessionInfo): ModelRef | undefined { + const configured = this.settingsService.getSettings().preferences.walkthroughModel?.trim() + const parsed = configured ? parseOpenCodeModelRef(configured) : undefined + return parsed ?? session.model + } } diff --git a/backend/test/routes/change-walkthroughs.test.ts b/backend/test/routes/change-walkthroughs.test.ts index 79daf244..38b77073 100644 --- a/backend/test/routes/change-walkthroughs.test.ts +++ b/backend/test/routes/change-walkthroughs.test.ts @@ -5,6 +5,7 @@ import type { FileDiffInfo, SessionInfo } from '@opencode-manager/shared/opencod import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import { ChangeWalkthroughService, computeHunkId } from '../../src/services/change-walkthroughs' +import { SettingsService } from '../../src/services/settings' import { createChangeWalkthroughRoutes } from '../../src/routes/change-walkthroughs' import type { OpenCodeClient } from '../../src/services/opencode/client' import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client' @@ -93,7 +94,7 @@ describe('change walkthrough routes', () => { migrate(db, allMigrations) sessions = { [SESSION_ID]: { changes: CHANGES } } fake = createFakeClient(sessions) - const service = new ChangeWalkthroughService(db, fake.client) + const service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db)) app = new Hono() app.route('/change-walkthroughs', createChangeWalkthroughRoutes(service)) }) diff --git a/backend/test/routes/internal-settings.test.ts b/backend/test/routes/internal-settings.test.ts index a9e87b75..75f5bf90 100644 --- a/backend/test/routes/internal-settings.test.ts +++ b/backend/test/routes/internal-settings.test.ts @@ -353,4 +353,19 @@ describe('internal/settings routes', () => { expect(body.preferences.theme).toBe('light') expect(body.preferences.mode).toBe('plan') }) + + it('PATCH /api/internal/settings with { walkthroughModel } persists it', async () => { + const res = await app.request('/api/internal/settings', { + method: 'PATCH', + body: JSON.stringify({ walkthroughModel: 'openai/gpt-5-mini' }), + headers: { + 'content-type': 'application/json', + authorization: `Bearer ${token}`, + }, + }) + expect(res.status).toBe(200) + const body = await res.json() as { preferences: { walkthroughModel?: string } } + expect(body.preferences.walkthroughModel).toBe('openai/gpt-5-mini') + expect(settingsService.getSettings().preferences.walkthroughModel).toBe('openai/gpt-5-mini') + }) }) diff --git a/backend/test/services/change-walkthroughs.test.ts b/backend/test/services/change-walkthroughs.test.ts index 6d17a21c..b7d84533 100644 --- a/backend/test/services/change-walkthroughs.test.ts +++ b/backend/test/services/change-walkthroughs.test.ts @@ -14,6 +14,7 @@ import { getChangeWalkthrough } from '../../src/db/change-walkthroughs' import { migrate } from '../../src/db/migration-runner' import { allMigrations } from '../../src/db/migrations' import type { OpenCodeClient } from '../../src/services/opencode/client' +import { SettingsService } from '../../src/services/settings' import type { SSEEvent } from '../../src/services/sse-aggregator' import { stubLoadedModelCatalog } from '../helpers/stub-opencode-client' import { @@ -783,7 +784,7 @@ describe('ChangeWalkthroughService', () => { db = createTestDb() sessions = { [SESSION_ID]: { changes: threeHunks } } fake = createFakeClient(sessions) - service = new ChangeWalkthroughService(db, fake.client) + service = new ChangeWalkthroughService(db, fake.client, new SettingsService(db)) }) afterEach(() => { @@ -964,6 +965,31 @@ describe('ChangeWalkthroughService', () => { expect(fake.generateModels[0]).toEqual({ providerID: 'openai', id: 'gpt-5-mini' }) }) + it('uses the walkthrough model preference', async () => { + new SettingsService(db).updateSettings({ walkthroughModel: 'openai/gpt-5-mini' }) + fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }])) + + const { walkthrough } = await service.generate(SESSION_ID, {}) + + expect(fake.generateModels.every((model) => model?.providerID === 'openai' && model.id === 'gpt-5-mini')).toBe(true) + expect(fake.generateModels.length).toBeGreaterThan(0) + expect(walkthrough.model).toBe('openai/gpt-5-mini') + }) + + it('ignores an invalid walkthrough model preference', async () => { + new SettingsService(db).updateSettings({ walkthroughModel: 'not-a-ref' }) + sessions[SESSION_ID]!.info = { + id: SESSION_ID, + title: 'Title', + model: { providerID: 'anthropic', id: 'claude-sonnet-4' }, + } as SessionInfo + fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }])) + + await service.generate(SESSION_ID, {}) + + expect(fake.generateModels[0]).toEqual({ providerID: 'anthropic', id: 'claude-sonnet-4' }) + }) + it('coalesces concurrent generation into one model call', async () => { let resolveGenerate: (text: string) => void = () => {} const gate = new Promise((resolve) => { @@ -1027,7 +1053,7 @@ describe('ChangeWalkthroughService', () => { }) it('rejects with 504 when generation times out', async () => { - const timingOut = new ChangeWalkthroughService(db, fake.client, { timeoutMs: 5 }) + const timingOut = new ChangeWalkthroughService(db, fake.client, new SettingsService(db), { timeoutMs: 5 }) fake.setGenerateImpl(() => new Promise(() => {})) await expect(timingOut.generate(SESSION_ID, {})).rejects.toMatchObject({ diff --git a/shared/src/schemas/internal-assistant.ts b/shared/src/schemas/internal-assistant.ts index 86758fcd..9c00f595 100644 --- a/shared/src/schemas/internal-assistant.ts +++ b/shared/src/schemas/internal-assistant.ts @@ -51,6 +51,7 @@ export const AssistantSettingsPatchSchema = UserPreferencesSchema.pick({ colorTheme: true, mode: true, defaultModel: true, + walkthroughModel: true, defaultAgent: true, autoScroll: true, expandDiffs: true, diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index fa0ed2df..d2921e37 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -177,6 +177,7 @@ export const UserPreferencesSchema = z.object({ colorTheme: ColorThemeIdSchema.optional(), mode: z.enum(["plan", "build"]), defaultModel: z.string().optional(), + walkthroughModel: z.string().optional(), defaultAgent: z.string().optional(), autoScroll: z.boolean(), expandDiffs: z.boolean(),