feat: own model and effort for script generation and AI review (#12678)

* feat: own model and effort for script generation and AI review

* fix: mark the picked model by provider too in the model menu
This commit is contained in:
AlexRV12
2026-11-26 17:26:45 +01:00
committed by GitHub
parent f28bdff94f
commit 51cd51cd52
9 changed files with 309 additions and 148 deletions
+63 -18
View File
@@ -15,10 +15,16 @@ import {
WorkspaceService
} from './gen'
import {
AI_REVIEW_MODEL_SETTING_NAME,
AI_REVIEW_PROVIDER_SETTING_NAME,
AI_REVIEW_REASONING_SETTING_NAME,
aiUserDisabled,
COPILOT_SESSION_MODEL_SETTING_NAME,
COPILOT_SESSION_PROVIDER_SETTING_NAME,
COPILOT_SESSION_REASONING_SETTING_NAME
COPILOT_SESSION_REASONING_SETTING_NAME,
SCRIPT_GEN_MODEL_SETTING_NAME,
SCRIPT_GEN_PROVIDER_SETTING_NAME,
SCRIPT_GEN_REASONING_SETTING_NAME
} from './stores'
import { getLocalSetting, storeLocalSetting } from './utils'
import {
@@ -28,20 +34,51 @@ import {
const USER_CUSTOM_PROMPTS_KEY = 'userCustomAIPrompts'
const sessionModel = getLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME)
const sessionProvider = getLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME)
const sessionReasoning = getLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME)
export const copilotSessionModel = writable<ReasoningProviderModel | undefined>(
sessionModel && sessionProvider
? {
// Strip the deprecated /thinking suffix on read; the default effort
// (resolved later) restores reasoning for migrated selections.
model: stripLegacyThinkingSuffix(sessionModel),
provider: sessionProvider as AIProvider,
...(sessionReasoning ? { reasoning: sessionReasoning } : {})
}
: undefined
)
type PickSettings = { model: string; provider: string; reasoning: string }
const LAST_PICK_SETTINGS: PickSettings = {
model: COPILOT_SESSION_MODEL_SETTING_NAME,
provider: COPILOT_SESSION_PROVIDER_SETTING_NAME,
reasoning: COPILOT_SESSION_REASONING_SETTING_NAME
}
const SCRIPT_GEN_PICK_SETTINGS: PickSettings = {
model: SCRIPT_GEN_MODEL_SETTING_NAME,
provider: SCRIPT_GEN_PROVIDER_SETTING_NAME,
reasoning: SCRIPT_GEN_REASONING_SETTING_NAME
}
const AI_REVIEW_PICK_SETTINGS: PickSettings = {
model: AI_REVIEW_MODEL_SETTING_NAME,
provider: AI_REVIEW_PROVIDER_SETTING_NAME,
reasoning: AI_REVIEW_REASONING_SETTING_NAME
}
function readStoredPick(settings: PickSettings): ReasoningProviderModel | undefined {
const model = getLocalSetting(settings.model)
const provider = getLocalSetting(settings.provider)
const reasoning = getLocalSetting(settings.reasoning)
if (!model || !provider) return undefined
return {
// Strip the deprecated /thinking suffix on read; the default effort
// (resolved later) restores reasoning for migrated selections.
model: stripLegacyThinkingSuffix(model),
provider: provider as AIProvider,
...(reasoning ? { reasoning } : {})
}
}
function storePick(settings: PickSettings, pick: ReasoningProviderModel) {
storeLocalSetting(settings.model, pick.model)
storeLocalSetting(settings.provider, pick.provider)
storeLocalSetting(settings.reasoning, pick.reasoning)
}
export const copilotSessionModel = writable(readStoredPick(LAST_PICK_SETTINGS))
// Script generation's own pick, which neither follows nor sets the last pick.
export const scriptGenModel = writable(readStoredPick(SCRIPT_GEN_PICK_SETTINGS))
// AI review's own pick outside a session; inside one, a review starts on the session's model.
export const aiReviewModel = writable(readStoredPick(AI_REVIEW_PICK_SETTINGS))
export type CopilotInfo = {
enabled: boolean
@@ -304,9 +341,17 @@ export function invalidateWorkspaceCopilotInfo(workspace?: string) {
* until it has one. */
export function setLastModelPick(model: ReasoningProviderModel) {
copilotSessionModel.set(model)
storeLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME, model.model)
storeLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME, model.provider)
storeLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME, model.reasoning)
storePick(LAST_PICK_SETTINGS, model)
}
export function setScriptGenModelPick(model: ReasoningProviderModel) {
scriptGenModel.set(model)
storePick(SCRIPT_GEN_PICK_SETTINGS, model)
}
export function setAiReviewModelPick(model: ReasoningProviderModel) {
aiReviewModel.set(model)
storePick(AI_REVIEW_PICK_SETTINGS, model)
}
// Leaves copilotSessionModel alone: the pick is shared with sessions in other workspaces, which may
@@ -22,10 +22,14 @@
import { AlertTriangle, Ban, Check, ExternalLink, HistoryIcon, Wand2, X } from 'lucide-svelte'
import { fade } from 'svelte/transition'
import { isInitialCode } from '$lib/script_helpers'
import { twMerge } from 'tailwind-merge'
import { onDestroy, type ComponentProps } from 'svelte'
import ProviderModelSelector from './chat/ProviderModelSelector.svelte'
import { copilotInfo } from '$lib/aiStore'
import {
copilotInfo,
scriptGenModel,
setScriptGenModelPick,
tryResolveModelFor
} from '$lib/aiStore'
interface Props {
// props
@@ -62,6 +66,7 @@
let generatedCode = writable<string>('')
let dbSchema: DBSchema | undefined = $state(undefined)
let abortController: AbortController | undefined = $state(undefined)
let model = $derived(tryResolveModelFor($copilotInfo, $scriptGenModel))
let blockPopupOpen = $state(false)
let mode: 'gen' | 'edit' = $state('gen')
@@ -71,34 +76,19 @@
trimmedDesc = funcDesc.trim()
})
async function callCopilot() {
if (mode === 'edit') {
await copilot(
{
// @ts-ignore
language: transformer && lang === 'frontend' ? 'transformer' : lang!,
description: trimmedDesc,
code: editor?.getCode() || '',
dbSchema: dbSchema,
type: 'edit',
workspace: $workspaceStore!
},
generatedCode,
abortController!
)
} else {
await copilot(
{
// @ts-ignore
language: transformer && lang === 'frontend' ? 'transformer' : lang!,
description: trimmedDesc,
dbSchema: dbSchema,
type: 'gen',
workspace: $workspaceStore!
},
generatedCode,
abortController!
)
}
await copilot(
{
// @ts-ignore
language: transformer && lang === 'frontend' ? 'transformer' : lang!,
description: trimmedDesc,
dbSchema: dbSchema,
workspace: $workspaceStore!,
...(mode === 'edit' ? { type: 'edit', code: editor?.getCode() || '' } : { type: 'gen' })
},
generatedCode,
abortController!,
{ forceModelProvider: model }
)
}
function handleAiButtonClick() {
@@ -132,13 +122,13 @@
showDiff()
funcDesc = ''
} catch (err) {
if (!abortController?.signal.aborted) {
if (err?.message) {
sendUserToast('Failed to generate code: ' + err.message, true)
} else {
sendUserToast('Failed to generate code', true)
console.error(err)
}
if (abortController?.signal.aborted) {
clear()
} else if (err?.message) {
sendUserToast('Failed to generate code: ' + err.message, true)
} else {
sendUserToast('Failed to generate code', true)
console.error(err)
}
} finally {
genLoading = false
@@ -364,39 +354,38 @@
]
}}
disabled={blockPopupOpen}
onClose={() => {
// Escape or a click on the overlay closes the box mid-request, taking its Stop with it.
if (blockPopupOpen) abortController?.abort()
}}
>
{#snippet trigger()}
{#if inlineScript}
<Button
size="xs"
color={genLoading ? 'red' : 'light'}
btnClasses={twMerge(genLoading ? '!px-3 z-[5000]' : '!px-2')}
propagateEvent={!genLoading}
on:click={genLoading ? () => abortController?.abort() : handleAiButtonClick}
unifiedSize="sm"
variant="subtle"
btnClasses="!px-2"
disabled={genLoading}
on:click={handleAiButtonClick}
bind:element={button}
iconOnly
title="Generate code from prompt"
startIcon={genLoading ? { icon: Ban } : { icon: Wand2, classes: 'text-ai' }}
startIcon={{ icon: Wand2, classes: 'text-ai' }}
{...btnProps}
/>
{:else}
<Button
title="Generate code from prompt"
btnClasses={twMerge('!font-medium', genLoading ? 'z-[5000]' : 'text-ai')}
size="xs"
color={genLoading ? 'red' : 'light'}
spacingSize="md"
startIcon={genLoading ? { icon: Ban } : { icon: Wand2 }}
propagateEvent={!genLoading}
on:click={genLoading ? () => abortController?.abort() : handleAiButtonClick}
btnClasses="!font-medium text-ai"
unifiedSize="sm"
variant="subtle"
startIcon={{ icon: Wand2 }}
disabled={genLoading}
on:click={handleAiButtonClick}
bind:element={button}
{...btnProps}
>
{#if genLoading}
Stop
{:else}
AI Gen
{/if}
AI Gen
</Button>
{/if}
{/snippet}
@@ -412,18 +401,24 @@
<LoadingIcon />
{/if}
</div>
<div class="flex justify-end pt-2">
<Button
unifiedSize="sm"
variant="default"
startIcon={{ icon: Ban }}
onClick={() => abortController?.abort()}
>
Stop
</Button>
</div>
{:else if $copilotInfo.enabled}
<div class="flex flex-col gap-4">
<div class="flex flex-row justify-between items-center w-96 gap-2">
<ToggleButtonGroup class="w-auto shrink-0 h-auto" bind:selected={mode}>
{#snippet children({ item })}
<ToggleButton value={'gen'} label="Generate from scratch" class="px-2" {item} />
<ToggleButton value={'edit'} label="Edit existing code" class="px-2" {item} />
{/snippet}
</ToggleButtonGroup>
<ProviderModelSelector />
</div>
<ToggleButtonGroup class="w-auto self-start h-auto" bind:selected={mode}>
{#snippet children({ item })}
<ToggleButton value={'gen'} label="Generate from scratch" class="px-2" {item} />
<ToggleButton value={'edit'} label="Edit existing code" class="px-2" {item} />
{/snippet}
</ToggleButtonGroup>
<div class="flex w-96 items-start">
<textarea
bind:this={input}
@@ -456,6 +451,9 @@
startIcon={{ icon: Wand2 }}
/>
</div>
<div class="flex w-96 justify-end items-center gap-1 -mt-3">
<ProviderModelSelector {model} onPick={setScriptGenModelPick} />
</div>
{#if promptHistory.length > 0}
<div class="w-96 flex flex-col gap-1">
{#each promptHistory as p}
@@ -2,14 +2,8 @@
import { ChevronDown, Brain } from 'lucide-svelte'
import DropdownV2 from '$lib/components/DropdownV2.svelte'
import Button from '$lib/components/common/button/Button.svelte'
import {
COPILOT_SESSION_MODEL_SETTING_NAME,
COPILOT_SESSION_PROVIDER_SETTING_NAME,
COPILOT_SESSION_REASONING_SETTING_NAME
} from '$lib/stores'
import { storeLocalSetting } from '$lib/utils'
import { copilotInfo, copilotSessionModel, tryResolveModelFor } from '$lib/aiStore'
import type { AIProvider } from '$lib/gen'
import { copilotInfo } from '$lib/aiStore'
import type { AIProvider, AIProviderModel } from '$lib/gen'
import {
getReasoningCapability,
resolveEffectiveReasoning,
@@ -17,14 +11,25 @@
type ReasoningProviderModel
} from '../reasoningRegistry'
interface Props {
/** The model a request would send, as resolved from the pick. */
model: ReasoningProviderModel | undefined
onPick: (pick: ReasoningProviderModel) => void
/** The models offered, when they are not the tab's workspace's (an AI session's). */
models?: AIProviderModel[]
}
let { model, onPick, models }: Props = $props()
let offered = $derived(models ?? $copilotInfo.aiModels)
let providerModel = $derived(
(tryResolveModelFor($copilotInfo, $copilotSessionModel) ?? {
(model ?? {
model: 'No model',
provider: 'No provider'
}) as ReasoningProviderModel
)
let multipleModels = $derived($copilotInfo.aiModels.length > 1)
let multipleModels = $derived(offered.length > 1)
let capability = $derived(
getReasoningCapability(providerModel.provider as AIProvider, providerModel.model)
@@ -35,25 +40,17 @@
let effortLabel = $derived(currentEffort ?? REASONING_OFF)
function selectReasoning(value: string) {
const reasoning = value === REASONING_OFF ? REASONING_OFF : value
$copilotSessionModel = {
...providerModel,
provider: providerModel.provider as AIProvider,
reasoning
}
// Pin the current model selection so the reasoning choice persists with it.
storeLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME, providerModel.model)
storeLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME, providerModel.provider)
storeLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME, reasoning)
onPick({ ...providerModel, reasoning: value })
}
</script>
{#if multipleModels}
<DropdownV2
items={() =>
$copilotInfo.aiModels.map((m) => ({
offered.map((m) => ({
displayName: m.model,
selected: m.model === providerModel.model,
selected: m.model === providerModel.model && m.provider === providerModel.provider,
action: () => {
// Carry the effort onto the new model only if it supports that level
// ('off' only where the model can truly disable); otherwise drop it so
@@ -64,10 +61,7 @@
carried === REASONING_OFF
? cap.canDisable
: carried !== undefined && cap.levels.includes(carried)
$copilotSessionModel = { ...m, ...(keep ? { reasoning: carried } : {}) }
storeLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME, m.model)
storeLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME, m.provider)
storeLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME, keep ? carried : undefined)
onPick({ ...m, ...(keep ? { reasoning: carried } : {}) })
}
}))}
placement="bottom-end"
+34 -12
View File
@@ -25,9 +25,11 @@ import {
completionsRejectsToolsWithReasoning,
explicitOffToken,
requestsReasoning,
resolveRequestReasoning,
stripLegacyThinkingSuffix,
usesOpenAIResponsesApi,
type ReasoningEffort
type ReasoningEffort,
type ReasoningProviderModel
} from './reasoningRegistry'
import { formatResourceTypes } from './utils'
import {
@@ -604,6 +606,7 @@ interface AnthropicCompletionParams {
resourcePath?: string
resourceValue?: Record<string, any>
maxTokensCap?: number
reasoningEffort?: ReasoningEffort
info?: CopilotInfo
}
@@ -615,6 +618,7 @@ function buildAnthropicProxyRequest({
resourcePath,
resourceValue,
maxTokensCap,
reasoningEffort,
info
}: Omit<AnthropicCompletionParams, 'abortController'>) {
const { system, messages: anthropicMessages } = convertOpenAIToAnthropicMessages(messages)
@@ -633,12 +637,16 @@ function buildAnthropicProxyRequest({
? workspaceAIClients.createAnthropicClient(workspace)
: workspaceAIClients.getAnthropicClient()
const body = {
model: modelProvider.model,
max_tokens: resolveMaxTokens(modelProvider, maxTokensCap, undefined, info),
messages: anthropicMessages,
...(system && { system })
}
const body = applyReasoningToConfig(
{
model: modelProvider.model,
max_tokens: resolveMaxTokens(modelProvider, maxTokensCap, reasoningEffort, info),
messages: anthropicMessages,
...(system && { system })
},
'anthropic',
reasoningEffort
)
return { client, headers, body }
}
@@ -900,7 +908,7 @@ export function modelSupportsWebSearch(provider: AIProvider | undefined, model:
}
/** The model a request that names none sends: `info`'s workspace's default when given, else the
* tab's. */
* last pick. */
function modelFor(info: CopilotInfo | undefined): AIProviderModel {
return info ? resolveModelFor(info, undefined) : getCurrentModel()
}
@@ -1147,6 +1155,7 @@ export async function getCompletion(
modelProvider,
abortController,
maxTokensCap: options?.maxTokensCap,
reasoningEffort: options?.reasoningEffort,
workspace: options?.workspace,
info: options?.info
})
@@ -1224,7 +1233,11 @@ export async function getStreamedCompletionText(
messages: ChatCompletionMessageParam[],
abortController: AbortController,
// `workspace` and `info` send it for that workspace, with its AI config, rather than the tab's.
options?: Partial<AiTarget> & { maxTokensCap?: number; forceModelProvider?: AIProviderModel }
options?: Partial<AiTarget> & {
maxTokensCap?: number
forceModelProvider?: AIProviderModel
reasoningEffort?: ReasoningEffort
}
): Promise<string> {
const modelProvider = options?.forceModelProvider ?? modelFor(options?.info)
const drain = async (forceCompletions: boolean) => {
@@ -1232,6 +1245,7 @@ export async function getStreamedCompletionText(
forceCompletions,
forceModelProvider: modelProvider,
maxTokensCap: options?.maxTokensCap,
reasoningEffort: options?.reasoningEffort,
workspace: options?.workspace,
info: options?.info
})
@@ -1567,15 +1581,16 @@ export async function parseOpenAICompletion(
}
export function getResponseFromEvent(part: OpenAI.Chat.Completions.ChatCompletionChunk): string {
return part.choices?.[0]?.delta?.content || ''
return splitContentDelta(part.choices?.[0]?.delta?.content).text
}
export async function copilot(
scriptOptions: CopilotOptions,
generatedCode: Writable<string>,
abortController: AbortController,
generatedExplanation?: Writable<string>
options?: { forceModelProvider?: ReasoningProviderModel; generatedExplanation?: Writable<string> }
) {
const { forceModelProvider, generatedExplanation } = options ?? {}
const { prompt, systemPrompt } = await getPrompts(scriptOptions)
const completion = await getCompletion(
@@ -1589,7 +1604,12 @@ export async function copilot(
content: prompt
}
],
abortController
abortController,
undefined,
{
forceModelProvider,
reasoningEffort: forceModelProvider && resolveRequestReasoning(forceModelProvider)
}
)
let response = ''
@@ -1643,6 +1663,8 @@ export async function copilot(
generatedCode.set(code)
}
}
// See `getStreamedCompletionText`: an aborted stream ends without throwing.
abortController.signal.throwIfAborted()
// make sure we display the latest and complete code
generatedCode.set(code)
@@ -0,0 +1,71 @@
import { afterEach, expect, it, vi } from 'vitest'
import { flushSync, mount, tick, unmount } from 'svelte'
import { get } from 'svelte/store'
import {
copilotSessionModel,
setCopilotInfo,
setLastModelPick,
setScriptGenModelPick
} from '$lib/aiStore'
import ScriptGen from './ScriptGen.svelte'
import { workspaceAIClients } from './lib'
vi.mock('$app/navigation', () => ({
goto: vi.fn(),
afterNavigate: vi.fn(),
beforeNavigate: vi.fn()
}))
// jsdom has no Element.animate.
vi.mock('svelte/transition', async (importOriginal) => ({
...(await importOriginal<typeof import('svelte/transition')>()),
fade: () => ({ duration: 0 })
}))
vi.mock('monaco-editor', () => ({ Selection: class Selection {}, editor: {} }))
let component: ReturnType<typeof mount> | undefined
afterEach(() => component && unmount(component))
it('sends its own model and effort, whatever the last pick is', async () => {
setCopilotInfo({
providers: {
anthropic: {
resource_path: 'u/admin/a',
models: ['claude-sonnet-4-6', 'claude-opus-4-6', 'claude-opus-4-8']
}
},
default_model: { provider: 'anthropic', model: 'claude-sonnet-4-6' }
})
const stream = vi.fn((_body: any) =>
(async function* () {
yield {
type: 'content_block_delta',
delta: { type: 'text_delta', text: '```bash\necho\n```' }
}
})()
)
vi.spyOn(workspaceAIClients, 'getAnthropicClient').mockReturnValue({
messages: { stream }
} as any)
component = mount(ScriptGen, {
target: document.body,
props: { lang: 'bash', editor: undefined, diffEditor: undefined, args: {} }
})
const lastPick = { provider: 'anthropic', model: 'claude-opus-4-8' } as const
setLastModelPick(lastPick)
setScriptGenModelPick({ provider: 'anthropic', model: 'claude-opus-4-6', reasoning: 'low' })
flushSync()
document.querySelector<HTMLButtonElement>('button[title="Generate code from prompt"]')!.click()
await vi.waitFor(() => expect(document.querySelector('textarea')).toBeTruthy())
const input = document.querySelector('textarea')!
input.value = 'say hi'
input.dispatchEvent(new Event('input', { bubbles: true }))
await tick()
input.dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true }))
await vi.waitFor(() => expect(stream).toHaveBeenCalled())
const body = stream.mock.calls[0][0]
expect(body.model).toBe('claude-opus-4-6')
expect(body.output_config?.effort).toBe('low')
expect(get(copilotSessionModel)).toEqual(lastPick)
})
@@ -2,12 +2,14 @@
import { Alert, Badge, Button } from '$lib/components/common'
import type { AIProviderModel } from '$lib/gen'
import {
aiReviewModel,
copilotInfo,
copilotSessionModel,
setAiReviewModelPick,
tryResolveModelFor,
type CopilotInfo
} from '$lib/aiStore'
import Select from '$lib/components/select/Select.svelte'
import ProviderModelSelector from '$lib/components/copilot/chat/ProviderModelSelector.svelte'
import type { ReasoningProviderModel } from '$lib/components/copilot/reasoningRegistry'
import { sendUserToast } from '$lib/toast'
import { logFeatureUsage } from '$lib/utils/featureUsage'
import { Loader2, MessageSquarePlus, Sparkles, WandSparkles, X } from 'lucide-svelte'
@@ -44,8 +46,8 @@
onPost?: (finding: AiReviewFinding) => Promise<void>
/** The reviewed workspace's AI config, when it is not the tab's (an AI session's). */
info?: CopilotInfo
/** The model to start on instead of the last pick (an AI session's own). */
defaultModel?: AIProviderModel
/** The model to start on instead of the review's own pick or the workspace default (an AI session's own). */
defaultModel?: ReasoningProviderModel
}
let { scope, source, onPost, info, defaultModel }: Props = $props()
@@ -71,14 +73,23 @@
let stale = $derived(reviewed != undefined && reviewed.key !== itemsKey(items))
const modelKey = (m: AIProviderModel) => `${m.provider}:${m.model}`
// Local to this review: picking a model here must not change the chat's own selection,
// which is only the default until something is picked.
let pickedModelKey = $state<string | undefined>(undefined)
// Neither follows nor sets the sessions' last pick. Outside a session the pick is remembered for
// the next review; inside one it stays local to this review.
let picked = $state<ReasoningProviderModel | undefined>(undefined)
let aiModels = $derived((info ?? $copilotInfo).aiModels)
let chatModel = $derived(
defaultModel ?? tryResolveModelFor(info ?? $copilotInfo, $copilotSessionModel)
let startModel = $derived(
defaultModel ?? tryResolveModelFor(info ?? $copilotInfo, $aiReviewModel)
)
let selectedModelKey = $derived(pickedModelKey ?? (chatModel && modelKey(chatModel)))
// A pick the reviewed workspace no longer offers gives way to the model the review started on.
let model = $derived.by(() => {
const pick = picked
return pick && aiModels.some((m) => modelKey(m) === modelKey(pick)) ? pick : startModel
})
function pickModel(pick: ReasoningProviderModel) {
picked = pick
if (!defaultModel) setAiReviewModelPick(pick)
}
async function run() {
abortController?.abort()
@@ -91,7 +102,7 @@
logFeatureUsage('deployment_request', 'ai_review', { key: source })
try {
const review = await reviewChanges(scope, controller, {
model: aiModels.find((m) => modelKey(m) === selectedModelKey),
model,
info
})
if (!controller.signal.aborted) result = review
@@ -217,14 +228,8 @@
>
{result ? 'Review again with AI' : 'Review with AI'}
</Button>
{#if aiModels.length > 1}
<div class="w-56">
<Select
size="sm"
items={aiModels.map((m) => ({ label: m.model, value: modelKey(m) }))}
bind:value={() => selectedModelKey, (v) => (pickedModelKey = v)}
/>
</div>
{#if model}
<ProviderModelSelector {model} onPick={pickModel} models={aiModels} />
{/if}
{#if items.length === 0}
<span class="text-xs text-secondary">
@@ -5,20 +5,22 @@ const h = vi.hoisted(() => ({
prompt: '',
system: '',
workspace: '' as string | undefined,
reasoningEffort: undefined as string | undefined,
reads: 0,
instructionReads: [] as string[],
listed: [] as string[]
}))
vi.mock('$lib/components/copilot/lib', () => ({
getNonStreamingCompletion: async (
getStreamedCompletionText: async (
messages: { content: string }[],
_abort: AbortController,
options?: { workspace?: string }
options?: { workspace?: string; reasoningEffort?: string }
) => {
h.system = messages[0].content
h.prompt = messages[1].content
h.workspace = options?.workspace
h.reasoningEffort = options?.reasoningEffort
return '{"summary":"s","findings":[]}'
}
}))
@@ -150,4 +152,19 @@ describe('drafts review', () => {
expect(h.workspace).toBe('parent')
expect(h.system).toContain('You review drafts in a Windmill workspace')
})
it('sends the effort picked with the model', async () => {
await reviewChanges(
{
kind: 'drafts',
workspaceId: 'parent',
items: [
{ kind: 'script', path: 'f/a/b', change: 'added', load: async () => ({ after: 'x' }) }
]
},
new AbortController(),
{ model: { provider: 'anthropic', model: 'claude-sonnet-4-6', reasoning: 'low' } }
)
expect(h.reasoningEffort).toBe('low')
})
})
@@ -1,6 +1,10 @@
import type { AIProviderModel, WorkspaceItemDiff } from '$lib/gen'
import type { WorkspaceItemDiff } from '$lib/gen'
import type { CopilotInfo } from '$lib/aiStore'
import { getNonStreamingCompletion } from '$lib/components/copilot/lib'
import { getStreamedCompletionText } from '$lib/components/copilot/lib'
import {
resolveRequestReasoning,
type ReasoningProviderModel
} from '$lib/components/copilot/reasoningRegistry'
import { getItemValue } from '$lib/utils_workspace_deploy'
import type { Kind } from '$lib/utils_deployable'
import {
@@ -9,7 +13,6 @@ import {
} from '$lib/components/copilot/chat/folderInstructions'
import {
instructionsCovering,
MAX_OUTPUT_TOKENS,
parseReviewAnswer,
renderItemValue,
REVIEW_INSTRUCTIONS_RESOURCE_TYPE,
@@ -186,8 +189,8 @@ export async function reviewChanges(
scope: ReviewScope,
abortController: AbortController,
options?: {
/** Defaults to the workspace default of `info`, or without it to the last pick. */
model?: AIProviderModel
/** Defaults to the workspace default of `info`. Without either, the last pick is sent. */
model?: ReasoningProviderModel
/** The reviewed workspace's AI config, when it is not the tab's. */
info?: CopilotInfo
}
@@ -220,7 +223,7 @@ export async function reviewChanges(
const instructions = await instructionsPromise
if (abortController.signal.aborted) throw new Error('aborted')
const answer = await getNonStreamingCompletion(
const answer = await getStreamedCompletionText(
[
{ role: 'system', content: reviewSystemPrompt(subject) + instructions.text },
{
@@ -236,8 +239,8 @@ export async function reviewChanges(
// Bound to the reviewed workspace: without `workspace` the call goes through whichever
// workspace the app has switched to by the time the item reads finish.
{
maxTokensCap: MAX_OUTPUT_TOKENS,
forceModelProvider: options?.model,
reasoningEffort: options?.model && resolveRequestReasoning(options.model),
workspace: workspaceId,
info: options?.info
}
+6
View File
@@ -218,6 +218,12 @@ export const CODE_COMPLETION_SETTING_NAME = 'codeCompletionSessionEnabled'
export const COPILOT_SESSION_MODEL_SETTING_NAME = 'copilotSessionModel'
export const COPILOT_SESSION_PROVIDER_SETTING_NAME = 'copilotSessionProvider'
export const COPILOT_SESSION_REASONING_SETTING_NAME = 'copilotSessionReasoning'
export const SCRIPT_GEN_MODEL_SETTING_NAME = 'scriptGenModel'
export const SCRIPT_GEN_PROVIDER_SETTING_NAME = 'scriptGenProvider'
export const SCRIPT_GEN_REASONING_SETTING_NAME = 'scriptGenReasoning'
export const AI_REVIEW_MODEL_SETTING_NAME = 'aiReviewModel'
export const AI_REVIEW_PROVIDER_SETTING_NAME = 'aiReviewProvider'
export const AI_REVIEW_REASONING_SETTING_NAME = 'aiReviewReasoning'
export const formatOnSave = writable<boolean>(
getLocalSetting(FORMAT_ON_SAVE_SETTING_NAME) != 'false'
)