feat(walkthrough): open the change walkthrough from an agent tool call

This commit is contained in:
Chris Scott committed 2026-10-09 11:03:21 -04:00
1 parent 3eb0b02203
commit aa1da8d608
26 files changed
+1367 -175

No files matched your search

+1 -1
View File
@@ -341,7 +341,7 @@ app.route('/api/auth-info', createAuthInfoRoutes(auth, db))
app.route('/api/health', createHealthRoutes(db, openCodeSupervisor))
app.route('/api/mcp-oauth-proxy', createMcpOauthProxyRoutes(openCodeClient, requireAuth))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService))
app.route('/api/internal', createInternalRoutes(db, scheduleService, notificationService, settingsService, openCodeClient, sessionPermissionModeService, repoWorkspaces, gitAuthService, sessionGoalService, multiRunService, changeWalkthroughService))
app.route('/api/opencode-proxy', createOpenCodeProxyRoutes(db, settingsService, upgradeWebSocket))
const protectedApi = new Hono()
+4
View File
@@ -19,11 +19,13 @@ import { createInternalGitCredentialsRoutes } from './git-credentials'
import { createInternalSandboxRoutes } from './sandbox'
import { createSessionGoalRoutes } from '../session-goals'
import { createMultiRunRoutes } from '../multi-runs'
import { createChangeWalkthroughRoutes } from '../change-walkthroughs'
import type { SessionPermissionModeService } from '../../services/session-permission-modes'
import type { RepoWorkspaceService } from '../../services/repo-workspace'
import type { GitAuthService } from '../../services/git-auth'
import type { SessionGoalService } from '../../services/session-goals'
import type { MultiRunService } from '../../services/multi-runs'
import type { ChangeWalkthroughService } from '../../services/change-walkthroughs'
export function createInternalRoutes(
db: Database,
@@ -36,6 +38,7 @@ export function createInternalRoutes(
gitAuthService: GitAuthService,
sessionGoals: SessionGoalService,
multiRuns: MultiRunService,
changeWalkthroughService: ChangeWalkthroughService,
) {
const app = new Hono()
app.use('/*', createInternalTokenMiddleware(db))
@@ -54,6 +57,7 @@ export function createInternalRoutes(
app.route('/opencode-workspaces', createInternalOpenCodeWorkspacesRoutes(db))
app.route('/sessions', createInternalSessionRoutes(db, openCodeClient, permissionModes, repoWorkspaces))
app.route('/assistant', createInternalAssistantRoutes(openCodeClient))
app.route('/change-walkthroughs', createChangeWalkthroughRoutes(changeWalkthroughService))
app.route('/git-credentials', createInternalGitCredentialsRoutes(db))
app.route('/sandbox', createInternalSandboxRoutes(db))
return app
@@ -1,5 +1,5 @@
import { z } from 'zod'
import { ASSISTANT_NOTIFICATION_LIMITS } from '@opencode-manager/shared/schemas'
import { ASSISTANT_NOTIFICATION_LIMITS, WalkthroughSourceSchema } from '@opencode-manager/shared/schemas'
export const MANAGER_TOOL_NAME = 'ocm'
@@ -40,7 +40,7 @@ export const MANAGER_TOOL_ALLOWED_ROUTES = [
const MANAGER_TOOL_ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] as const
const MANAGER_TOOL_ACTION_NAMES = ['send_notification', 'request'] as const
const MANAGER_TOOL_ACTION_NAMES = ['send_notification', 'request', 'open_walkthrough'] as const
const ManagerToolNotificationParamsSchema = z
.object({
@@ -62,9 +62,17 @@ const ManagerToolRequestParamsSchema = z
.strict()
.describe('Call an allow-listed OpenCode Manager internal API route.')
const ManagerToolWalkthroughParamsSchema = z
.object({
source: WalkthroughSourceSchema.optional().describe('The change source to walk through. Defaults to the changes in this session.'),
})
.strict()
.describe("Open the change Walkthrough for this session in the user's Manager window and start generating it if needed.")
const MANAGER_TOOL_ACTION_PARAMS_SCHEMAS: Record<(typeof MANAGER_TOOL_ACTION_NAMES)[number], z.ZodType> = {
send_notification: ManagerToolNotificationParamsSchema,
request: ManagerToolRequestParamsSchema,
open_walkthrough: ManagerToolWalkthroughParamsSchema,
}
export function parseAllowedRoute(route: string): { method: string; path: string } {
@@ -94,7 +102,11 @@ function buildManagerToolInputJsonSchema(): Record<string, unknown> {
.object({
action: z.enum(MANAGER_TOOL_ACTION_NAMES).describe('The OpenCode Manager action to perform.'),
params: z
.union([MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.send_notification, MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.request])
.union([
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.send_notification,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.request,
MANAGER_TOOL_ACTION_PARAMS_SCHEMAS.open_walkthrough,
])
.describe('The parameters for the chosen action.'),
})
.strict(),
@@ -114,6 +126,7 @@ function buildManagerToolDescription(): string {
'Actions:',
'- send_notification: send a push notification to every device the user has registered.',
'- request: call an allow-listed internal API route to read and manage settings, the OpenCode configuration file, repos (list, inspect, clone from a git URL with POST /repos and body { repoUrl, branch?, directoryName? }), OpenCode workspaces, sessions (list, create, follow up, read the latest reply, fork), and schedules.',
"- open_walkthrough: open the change Walkthrough panel for the current session in the user's Manager window, generating it if needed; use when the user asks to walk through, review or explain the changes.",
'Allowed request routes:',
]
.concat(MANAGER_TOOL_ALLOWED_ROUTES.map((route) => `- ${route}`))
@@ -221,6 +234,27 @@ var ACTIONS = {
return text || 'The request succeeded with an empty response body.'
},
},
open_walkthrough: {
run: async function (params, context) {
var body = params.source === undefined ? undefined : { source: params.source }
var state = await postInternalApi('/change-walkthroughs/' + encodeURIComponent(context.sessionID), body, context.signal)
var metadata = { openPanel: 'walkthrough' }
if (params.source !== undefined) {
metadata.source = params.source
}
if (state.generating === true) {
return {
content: 'Opened the walkthrough. It is generating; the user can page through it as stops are explained.',
metadata: metadata,
}
}
var stops = state.walkthrough && Array.isArray(state.walkthrough.stops) ? state.walkthrough.stops.length : 0
if (state.walkthrough) {
return { content: 'Opened the walkthrough (' + stops + ' stops).', metadata: metadata }
}
return { content: 'Opened the walkthrough.', metadata: metadata }
},
},
}
function assertParams(actionName, params) {
@@ -257,7 +291,11 @@ export default {
input: INPUT_SCHEMA,
options: { codemode: false },
execute: async function (input, context) {
return { content: await runAction(input, context) }
var result = await runAction(input, context)
if (result !== null && typeof result === 'object' && typeof result.content === 'string') {
return result
}
return { content: result }
},
})
})
+26 -1
View File
@@ -1,4 +1,5 @@
import type { ModelRef } from '@opencode-manager/shared/opencode'
import { formatOpenCodeModelRef } from '@opencode-manager/shared/opencode'
import { getOpenCodeGlobalConfigPath } from '@opencode-manager/shared/config/env'
import type { OpenCodeClient } from './client'
import { resolveOpenCodeModel } from '../opencode-models'
@@ -37,10 +38,34 @@ async function generateText(
input: { prompt: string; model?: ModelRef },
signal: AbortSignal,
): Promise<{ text: string }> {
const model = input.model ?? await resolveGenerateModel(client, signal)
if (input.model) {
await waitForGenerateModel(client, input.model, signal)
return client.api.generate.text({ prompt: input.prompt, model: input.model }, { signal })
}
const model = await resolveGenerateModel(client, signal)
return client.api.generate.text({ prompt: input.prompt, model }, { signal })
}
/**
* Waits for an explicitly requested model to appear in OpenCode's global config-location catalog, which loads lazily after OpenCode starts.
* Generation proceeds even if the wait times out or the model stays unconfigured, so OpenCode can surface its own error; an abort still propagates.
*/
async function waitForGenerateModel(
client: OpenCodeClient,
model: ModelRef,
signal: AbortSignal,
): Promise<void> {
try {
await resolveOpenCodeModel(client, getOpenCodeGlobalConfigPath(), {
signal,
preferredModel: formatOpenCodeModelRef(model),
})
} catch {
signal.throwIfAborted()
}
}
/** OpenCode serves generation from its global config location, so the model must be resolved there once its catalog has loaded. */
async function resolveGenerateModel(client: OpenCodeClient, signal: AbortSignal): Promise<ModelRef> {
const { providerID, id, variant } = await resolveOpenCodeModel(client, getOpenCodeGlobalConfigPath(), { signal })
@@ -13,6 +13,7 @@ type InternalTestAppOverrides = Partial<{
gitAuthService: CreateInternalRoutesParams[7]
sessionGoals: CreateInternalRoutesParams[8]
multiRuns: CreateInternalRoutesParams[9]
changeWalkthroughService: CreateInternalRoutesParams[10]
}>
export function createInternalTestApp(
@@ -30,5 +31,6 @@ export function createInternalTestApp(
overrides.gitAuthService ?? ({} as CreateInternalRoutesParams[7]),
overrides.sessionGoals ?? ({} as CreateInternalRoutesParams[8]),
overrides.multiRuns ?? ({} as CreateInternalRoutesParams[9]),
overrides.changeWalkthroughService ?? ({} as CreateInternalRoutesParams[10]),
)
}
@@ -25,7 +25,7 @@ export type GeneratedTool = {
name: string
description?: string
input?: unknown
execute?: (input: unknown, context: { signal: AbortSignal }) => Promise<unknown>
execute?: (input: unknown, context: { signal: AbortSignal; sessionID?: string }) => Promise<unknown>
[key: string]: unknown
}
+7 -5
View File
@@ -1,15 +1,17 @@
import { vi } from 'vitest'
import type { OpenCodeApi } from '@opencode-manager/shared/opencode'
import type { ModelInfo, OpenCodeApi } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from '../../src/services/opencode/client'
/** OpenCode API stubs for a catalog that has finished loading, so model resolution succeeds on the first poll. */
export function stubLoadedModelCatalog() {
const model = { providerID: 'openai', id: 'gpt-5-mini', enabled: true }
export function stubLoadedModelCatalog(models: ModelInfo[] = [
{ providerID: 'openai', id: 'gpt-5-mini', enabled: true } as ModelInfo,
]) {
const defaultModel = models[0] ?? null
return {
config: { get: vi.fn(async () => []) },
model: {
list: vi.fn(async () => ({ data: [model] })),
default: vi.fn(async () => ({ data: model })),
list: vi.fn(async () => ({ data: models })),
default: vi.fn(async () => ({ data: defaultModel })),
},
}
}
@@ -0,0 +1,84 @@
import { describe, it, expect, beforeEach, vi } from 'vitest'
import { Hono } from 'hono'
import { Database } from 'bun:sqlite'
import { allMigrations } from '../../src/db/migrations'
import { getOrCreateInternalToken } from '../../src/services/internal-token'
import { migrate } from '../../src/db/migration-runner'
import type { ChangeWalkthroughService } from '../../src/services/change-walkthroughs'
import { createInternalTestApp } from '../helpers/internal-test-app'
const SESSION_ID = 'ses_walkthrough'
describe('internal/change-walkthroughs routes', () => {
let db: Database
let app: Hono
let token: string
let startGeneration: ReturnType<typeof vi.fn>
let getState: ReturnType<typeof vi.fn>
beforeEach(() => {
db = new Database(':memory:')
migrate(db, allMigrations)
startGeneration = vi.fn(async () => ({
walkthrough: null,
currentDiffHash: 'hash',
stale: false,
generating: true,
error: null,
}))
getState = vi.fn(async () => ({
walkthrough: null,
currentDiffHash: 'hash',
stale: false,
generating: false,
error: null,
}))
app = new Hono()
app.route(
'/api/internal',
createInternalTestApp(db, { changeWalkthroughService: { startGeneration, getState } as unknown as ChangeWalkthroughService }),
)
token = getOrCreateInternalToken(db)
})
it('POST /api/internal/change-walkthroughs/:id returns 401 without a bearer token', async () => {
const res = await app.request(`/api/internal/change-walkthroughs/${SESSION_ID}`, { method: 'POST' })
expect(res.status).toBe(401)
expect(startGeneration).not.toHaveBeenCalled()
})
it('POST /api/internal/change-walkthroughs/:id starts generation with the session id and source', async () => {
const res = await app.request(`/api/internal/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
body: JSON.stringify({ source: { kind: 'staged' } }),
})
expect(res.status).toBe(202)
expect(startGeneration).toHaveBeenCalledTimes(1)
expect(startGeneration).toHaveBeenCalledWith(SESSION_ID, { source: { kind: 'staged' } })
await expect(res.json()).resolves.toMatchObject({ generating: true })
})
it('POST /api/internal/change-walkthroughs/:id accepts an empty body', async () => {
const res = await app.request(`/api/internal/change-walkthroughs/${SESSION_ID}`, {
method: 'POST',
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(202)
expect(startGeneration).toHaveBeenCalledWith(SESSION_ID, {})
})
it('GET /api/internal/change-walkthroughs/:id reads the requested source', async () => {
const res = await app.request(`/api/internal/change-walkthroughs/${SESSION_ID}?source=staged`, {
headers: { authorization: `Bearer ${token}` },
})
expect(res.status).toBe(200)
expect(getState).toHaveBeenCalledWith(SESSION_ID, { kind: 'staged' }, undefined)
})
})
@@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import path from 'node:path'
import { Database } from 'bun:sqlite'
import type { FileDiffInfo, ModelRef, SessionInfo, SessionMessageInfo } from '@opencode-manager/shared/opencode'
import type { FileDiffInfo, ModelInfo, ModelRef, SessionInfo, SessionMessageInfo } from '@opencode-manager/shared/opencode'
import {
MECHANICAL_TEXT_BUDGET,
WALKTHROUGH_DIFF_MAX_CHARS,
@@ -152,7 +152,11 @@ function createFakeClient(sessions: Record<string, FakeSession>) {
const client = {
api: {
...stubLoadedModelCatalog(),
...stubLoadedModelCatalog([
{ providerID: 'openai', id: 'gpt-5-mini', enabled: true },
{ providerID: 'anthropic', id: 'claude-sonnet-4', enabled: true },
{ providerID: 'openai', id: 'gpt-5', enabled: true },
] as ModelInfo[]),
session: {
get: vi.fn(async ({ sessionID }: { sessionID: string }) => {
const config = sessions[sessionID]
@@ -1169,13 +1173,14 @@ describe('ChangeWalkthroughService', () => {
it('returns the stored walkthrough without a model call when changes are unchanged', async () => {
fake.setGenerateImpl(async () => modelReply([{ title: 'A', explanation: 'x', hunkIds: THREE_HUNK_IDS }]))
const first = await service.generate(SESSION_ID, {})
const modelListCallsAfterFirst = vi.mocked(fake.client.api.model.list).mock.calls.length
const second = await service.generate(SESSION_ID, {})
expect(second.created).toBe(false)
expect(second.walkthrough).toEqual(first.walkthrough)
expect(fake.generateCalls).toHaveLength(1)
expect(vi.mocked(fake.client.api.model.list)).toHaveBeenCalledTimes(1)
expect(vi.mocked(fake.client.api.model.list)).toHaveBeenCalledTimes(modelListCallsAfterFirst)
})
it('calls the model again when regenerate is set', async () => {
@@ -1233,7 +1238,7 @@ describe('ChangeWalkthroughService', () => {
expect(fake.generateModels[0]).toEqual({ providerID: 'anthropic', id: 'claude-sonnet-4' })
})
it('resolves the default model once per generation', async () => {
it('reuses the resolved default model for every stop', async () => {
sessions[SESSION_ID]!.changes = LARGE_CHANGES
fake.setGenerateImpl((prompt) =>
Promise.resolve(prompt.includes(PLAN_MARKER) ? LARGE_PLAN_REPLY : EXPLANATION_REPLY),
@@ -1241,7 +1246,10 @@ describe('ChangeWalkthroughService', () => {
await service.generate(SESSION_ID, {})
expect(vi.mocked(fake.client.api.model.list)).toHaveBeenCalledTimes(1)
expect(fake.generateModels).toHaveLength(4)
expect(
fake.generateModels.every((model) => model?.providerID === 'openai' && model.id === 'gpt-5-mini'),
).toBe(true)
})
it('includes the resolved default model in the explanation key', async () => {
@@ -1762,6 +1770,7 @@ describe('ChangeWalkthroughService', () => {
expect(state.generating).toBe(true)
expect(state.error).toBeNull()
await vi.waitFor(() => expect(fake.generateCalls.length).toBeGreaterThan(2))
resolveGenerate(coveringReply)
await vi.waitFor(async () => {
expect((await service.getState(SESSION_ID)).generating).toBe(false)
@@ -17,7 +17,9 @@ type JsonSchema = {
required?: string[]
additionalProperties?: boolean
anyOf?: JsonSchema[]
oneOf?: JsonSchema[]
enum?: string[]
const?: string
maxLength?: number
minLength?: number
}
@@ -41,9 +43,23 @@ function requestParamsSchema(tool: GeneratedTool): JsonSchema {
return toolInputSchema(tool).properties?.params?.anyOf?.[1] ?? {}
}
async function runTool(tool: GeneratedTool, input: unknown): Promise<string> {
const result = (await tool.execute!(input, { signal: new AbortController().signal })) as { content: string }
return result.content
function walkthroughParamsSchema(tool: GeneratedTool): JsonSchema {
return toolInputSchema(tool).properties?.params?.anyOf?.[2] ?? {}
}
async function runToolResult(
tool: GeneratedTool,
input: unknown,
context: { sessionID?: string } = {},
): Promise<{ content: string; metadata?: Record<string, unknown> }> {
return (await tool.execute!(input, { signal: new AbortController().signal, sessionID: context.sessionID })) as {
content: string
metadata?: Record<string, unknown>
}
}
async function runTool(tool: GeneratedTool, input: unknown, context: { sessionID?: string } = {}): Promise<string> {
return (await runToolResult(tool, input, context)).content
}
function jsonResponse(body: unknown, { ok = true, status = 200 } = {}) {
@@ -92,14 +108,31 @@ describe('ocm-manager plugin', () => {
expect(schema.type).toBe('object')
expect(schema.required).toEqual(['action', 'params'])
expect(schema.additionalProperties).toBe(false)
expect(schema.properties?.action?.enum).toEqual(['send_notification', 'request'])
expect(schema.properties?.params?.anyOf).toHaveLength(2)
expect(schema.properties?.action?.enum).toEqual(['send_notification', 'request', 'open_walkthrough'])
expect(schema.properties?.params?.anyOf).toHaveLength(3)
expect(notificationParamsSchema(tool).required).toEqual(['title', 'body'])
expect(requestParamsSchema(tool).required).toEqual(['method', 'path'])
expect(walkthroughParamsSchema(tool).required).toBeUndefined()
expect(notificationParamsSchema(tool).additionalProperties).toBe(false)
expect(requestParamsSchema(tool).additionalProperties).toBe(false)
expect(walkthroughParamsSchema(tool).additionalProperties).toBe(false)
expect(notificationParamsSchema(tool).properties?.priority?.enum).toEqual(['normal', 'high'])
expect(requestParamsSchema(tool).properties?.method?.enum).toEqual(['GET', 'POST', 'PUT', 'PATCH', 'DELETE'])
expect(walkthroughParamsSchema(tool).properties?.source?.oneOf?.map((variant) => variant.properties?.kind?.const)).toEqual([
'session',
'uncommitted',
'staged',
'unstaged',
'branch',
'pullRequest',
])
})
it('lists the open_walkthrough action in the description', async () => {
const tool = await loadTool(configHome)
expect(tool.description).toContain('open_walkthrough')
expect(tool.description).toContain("open the change Walkthrough panel for the current session in the user's Manager window")
})
it('enforces the notification limits the internal API enforces', async () => {
@@ -191,6 +224,52 @@ describe('ocm-manager plugin', () => {
expect(fetchMock).not.toHaveBeenCalled()
})
it('opens the walkthrough for the current session with the requested source', async () => {
const fetchMock = jsonResponse({ walkthrough: { stops: [{}, {}] }, currentDiffHash: 'h', stale: false, generating: false, error: null })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
const result = await runToolResult(
tool,
{ action: 'open_walkthrough', params: { source: { kind: 'staged' } } },
{ sessionID: 'ses_abc' },
)
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toBe('http://localhost:5003/api/internal/change-walkthroughs/ses_abc')
expect(init.method).toBe('POST')
expect(init.headers.Authorization).toBe('Bearer secret-token')
expect(init.headers['content-type']).toBe('application/json')
expect(JSON.parse(init.body)).toEqual({ source: { kind: 'staged' } })
expect(result.content).toBe('Opened the walkthrough (2 stops).')
expect(result.metadata).toEqual({ openPanel: 'walkthrough', source: { kind: 'staged' } })
})
it('reports that the walkthrough is generating', async () => {
vi.stubGlobal('fetch', jsonResponse({ walkthrough: null, currentDiffHash: 'h', stale: false, generating: true, error: null }))
const tool = await loadTool(configHome)
const result = await runToolResult(tool, { action: 'open_walkthrough', params: {} }, { sessionID: 'ses_abc' })
expect(result.content).toBe('Opened the walkthrough. It is generating; the user can page through it as stops are explained.')
expect(result.metadata).toEqual({ openPanel: 'walkthrough' })
})
it('opens the walkthrough without a body when no source is given', async () => {
const fetchMock = jsonResponse({ walkthrough: null, currentDiffHash: 'h', stale: false, generating: true, error: null })
vi.stubGlobal('fetch', fetchMock)
const tool = await loadTool(configHome)
await runTool(tool, { action: 'open_walkthrough', params: {} }, { sessionID: 'ses_abc' })
expect(fetchMock).toHaveBeenCalledTimes(1)
const [url, init] = fetchMock.mock.calls[0] ?? []
expect(url).toBe('http://localhost:5003/api/internal/change-walkthroughs/ses_abc')
expect(init.headers['content-type']).toBeUndefined()
expect(init.body).toBeUndefined()
})
it('sends an allow-listed GET request with a query string and no body', async () => {
const fetchMock = jsonResponse({ userId: 'default', theme: 'dark' })
vi.stubGlobal('fetch', fetchMock)
@@ -522,7 +601,7 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
expect(managerTool?.function?.parameters).toMatchObject({
type: 'object',
properties: {
action: { type: 'string', enum: ['send_notification', 'request'] },
action: { type: 'string', enum: ['send_notification', 'request', 'open_walkthrough'] },
params: {
anyOf: [
{
@@ -545,6 +624,13 @@ describe.skipIf(SHIPPED_OPENCODE_BIN === null)('ocm-manager plugin against the s
body: { type: 'object' },
},
},
{
type: 'object',
additionalProperties: false,
properties: {
source: expect.anything(),
},
},
],
},
},
@@ -3,7 +3,7 @@ import { getOpenCodeGlobalConfigPath } from '@opencode-manager/shared/config/env
import type { ModelInfo, ModelRef } from '@opencode-manager/shared/opencode'
import type { OpenCodeClient } from '../../../src/services/opencode/client'
import { GenerateTextTimeoutError, generateTextWithTimeout } from '../../../src/services/opencode/generate-text'
import { MODEL_LOAD_POLL_MS } from '../../../src/services/opencode-models'
import { MODEL_LOAD_POLL_MS, MODEL_LOAD_TIMEOUT_MS } from '../../../src/services/opencode-models'
interface GenerateCall {
input: { prompt: string; model?: ModelRef }
@@ -77,14 +77,35 @@ describe('generateTextWithTimeout', () => {
expect(calls[0]?.input.model).toEqual({ providerID: 'openai', id: 'gpt-5-mini' })
})
it('forwards the model when provided without reading the catalog', async () => {
const { client, calls, modelList } = makeClient(async () => ({ text: 'hello' }))
const model: ModelRef = { providerID: 'anthropic', id: 'claude-sonnet-4' }
it('waits for the provided model to load before generating', async () => {
vi.useFakeTimers()
const model: ModelRef = { providerID: 'anthropic', id: 'claude-sonnet-4', variant: 'high' }
const { client, calls } = makeClient(async () => ({ text: 'hello' }), [
[],
[{ providerID: 'anthropic', id: 'claude-sonnet-4', enabled: true } as ModelInfo],
])
await generateTextWithTimeout(client, { prompt: 'write', model }, 1000)
const promise = generateTextWithTimeout(client, { prompt: 'write', model }, 10_000)
await vi.advanceTimersByTimeAsync(0)
expect(calls).toHaveLength(0)
await vi.advanceTimersByTimeAsync(MODEL_LOAD_POLL_MS)
await expect(promise).resolves.toBe('hello')
expect(calls).toHaveLength(1)
expect(calls[0]?.input).toEqual({ prompt: 'write', model })
})
it('generates with the provided model when its catalog never loads', async () => {
vi.useFakeTimers()
const model: ModelRef = { providerID: 'anthropic', id: 'claude-sonnet-4' }
const { client, calls } = makeClient(async () => ({ text: 'hello' }), [[]])
const promise = generateTextWithTimeout(client, { prompt: 'write', model }, 100_000)
await vi.advanceTimersByTimeAsync(MODEL_LOAD_TIMEOUT_MS)
await expect(promise).resolves.toBe('hello')
expect(calls).toHaveLength(1)
expect(calls[0]?.input).toEqual({ prompt: 'write', model })
expect(modelList).not.toHaveBeenCalled()
})
it('rejects with GenerateTextTimeoutError and aborts the request after the timeout', async () => {