mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 08:06:16 +00:00
feat: give each AI session its own model and effort (#12632)
* feat: give each AI session its own model and effort * fix: name the providers when a replaced model's name is the same
This commit is contained in:
@@ -166,6 +166,6 @@ it("keeps a model pick the tab's workspace does not offer, without sending it th
|
||||
setCopilotInfo(withModel('parent'))
|
||||
|
||||
expect(get(copilotSessionModel)).toEqual(pick)
|
||||
expect(tryResolveModelFor(get(copilotInfo))?.model).toBe('parent')
|
||||
expect(tryResolveModelFor(get(copilotInfo), pick)?.model).toBe('parent')
|
||||
copilotSessionModel.set(undefined)
|
||||
})
|
||||
|
||||
@@ -198,11 +198,14 @@ export function isWebSearchEnabledForProvider(
|
||||
}
|
||||
|
||||
export function getCurrentModel(): ReasoningProviderModel {
|
||||
return resolveModelFor(get(copilotInfo))
|
||||
return resolveModelFor(get(copilotInfo), get(copilotSessionModel))
|
||||
}
|
||||
|
||||
export function resolveModelFor(info: CopilotInfo): ReasoningProviderModel {
|
||||
const model = tryResolveModelFor(info)
|
||||
export function resolveModelFor(
|
||||
info: CopilotInfo,
|
||||
pick: ReasoningProviderModel | undefined
|
||||
): ReasoningProviderModel {
|
||||
const model = tryResolveModelFor(info, pick)
|
||||
if (!model) {
|
||||
throw new Error('No model selected')
|
||||
}
|
||||
@@ -222,7 +225,7 @@ export function resolveMetadataModelFor(info: CopilotInfo): AIProviderModel {
|
||||
}
|
||||
|
||||
export function tryGetCurrentModel(): ReasoningProviderModel | undefined {
|
||||
return tryResolveModelFor(get(copilotInfo))
|
||||
return tryResolveModelFor(get(copilotInfo), get(copilotSessionModel))
|
||||
}
|
||||
|
||||
/** `workspace`'s AI config if loaded; otherwise starts loading it and returns undefined. */
|
||||
@@ -297,6 +300,15 @@ export function invalidateWorkspaceCopilotInfo(workspace?: string) {
|
||||
}
|
||||
}
|
||||
|
||||
/** Sets the last pick, which everything without a pick of its own follows, a session included
|
||||
* 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)
|
||||
}
|
||||
|
||||
// Leaves copilotSessionModel alone: the pick is shared with sessions in other workspaces, which may
|
||||
// offer a model this one does not.
|
||||
export function setCopilotInfo(aiConfig: AIConfig) {
|
||||
@@ -307,11 +319,14 @@ function isOffered(info: CopilotInfo, model: AIProviderModel): boolean {
|
||||
return info.aiModels.some((m) => m.model === model.model && m.provider === model.provider)
|
||||
}
|
||||
|
||||
/** The model a request for `info`'s workspace sends: the shared pick when that workspace offers
|
||||
* it, else its default, else its first model. Never one the workspace does not offer. */
|
||||
export function tryResolveModelFor(info: CopilotInfo): ReasoningProviderModel | undefined {
|
||||
const picked = get(copilotSessionModel)
|
||||
if (picked && isOffered(info, picked)) return picked
|
||||
/** The model a request for `info`'s workspace sends: `pick` when that workspace offers it, else
|
||||
* its default, else its first model. Never a pick the workspace does not offer. `pick` is required
|
||||
* so that a session passes its own rather than silently following the shared one. */
|
||||
export function tryResolveModelFor(
|
||||
info: CopilotInfo,
|
||||
pick: ReasoningProviderModel | undefined
|
||||
): ReasoningProviderModel | undefined {
|
||||
if (pick && isOffered(info, pick)) return pick
|
||||
return info.defaultModel ?? info.aiModels[0]
|
||||
}
|
||||
|
||||
|
||||
@@ -402,6 +402,7 @@
|
||||
scope={aiReviewScope}
|
||||
source="draft_diff"
|
||||
info={aiChat.loadedSessionAiTarget?.info}
|
||||
defaultModel={aiChat.isSessionChat ? aiChat.currentModel : undefined}
|
||||
/>
|
||||
{/key}
|
||||
</div>
|
||||
|
||||
@@ -105,6 +105,7 @@ import {
|
||||
getWorkspaceCopilotInfo,
|
||||
loadWorkspaceCopilotInfo,
|
||||
resolveModelFor,
|
||||
setLastModelPick,
|
||||
tryResolveModelFor,
|
||||
workspaceCopilotInfoFailed,
|
||||
type AiTarget,
|
||||
@@ -841,6 +842,13 @@ export class AIChatManager implements ChatViewHost {
|
||||
* Set before `moving`, which waits for the editors to hand over their pending edits. */
|
||||
moveStarted = $state(false)
|
||||
onWorkModeChanged: ((mode: AIWorkMode) => void) | undefined = undefined
|
||||
/** The model and effort the session record holds. Unset outside sessions. */
|
||||
modelPickResolver: (() => ReasoningProviderModel | undefined) | undefined = undefined
|
||||
onModelPicked: ((model: ReasoningProviderModel) => void) | undefined = undefined
|
||||
/** `replaced`: the pick `model` stands in for, when the workspace does not offer it. */
|
||||
onModelSettled:
|
||||
| ((model: ReasoningProviderModel, replaced: ReasoningProviderModel | undefined) => void)
|
||||
| undefined = undefined
|
||||
/** The protected workspace the session was opted into working in directly (`direct_in`). */
|
||||
directInResolver: (() => string | undefined) | undefined = undefined
|
||||
get directIn(): string | undefined {
|
||||
@@ -1161,10 +1169,28 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
|
||||
get currentModel(): ReasoningProviderModel | undefined {
|
||||
// Subscribes only: the model helpers read through `get()`, which tracks nothing.
|
||||
void this.#sessionModel.current
|
||||
const info = this.aiInfo
|
||||
return info && tryResolveModelFor(info)
|
||||
return info && tryResolveModelFor(info, this.#modelPick)
|
||||
}
|
||||
|
||||
/** A session's own once it has one, so that a pick in another chat never moves it. */
|
||||
get #modelPick(): ReasoningProviderModel | undefined {
|
||||
return this.modelPickResolver?.() ?? this.#sessionModel.current
|
||||
}
|
||||
|
||||
/** The user picks `model` for this chat. It is also the one new sessions start on. */
|
||||
pickModel = (model: ReasoningProviderModel) => {
|
||||
this.onModelPicked?.(model)
|
||||
setLastModelPick(model)
|
||||
}
|
||||
|
||||
/** Pins a session to the model it sends with, so that nothing but a pick moves it from here on.
|
||||
* A pick its workspace does not offer is replaced for good: offered again, it stays replaced. */
|
||||
#settleModel() {
|
||||
const own = this.modelPickResolver?.()
|
||||
const model = this.currentModel
|
||||
if (!model || (own?.model === model.model && own.provider === model.provider)) return
|
||||
this.onModelSettled?.(model, own)
|
||||
}
|
||||
|
||||
/** Resolved at each request, after any fork commit. Undefined for other chats, whose requests
|
||||
@@ -1935,7 +1961,11 @@ export class AIChatManager implements ChatViewHost {
|
||||
{ role: 'user', content: getCompactionSummaryPrompt() }
|
||||
],
|
||||
abortController,
|
||||
{ maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS, ...target }
|
||||
{
|
||||
maxTokensCap: SUMMARY_OUTPUT_RESERVE_TOKENS,
|
||||
...target,
|
||||
forceModelProvider: target && resolveModelFor(target.info, this.#modelPick)
|
||||
}
|
||||
)
|
||||
const formatted = formatCompactSummary(raw)
|
||||
if (!formatted) {
|
||||
@@ -2190,6 +2220,9 @@ export class AIChatManager implements ChatViewHost {
|
||||
this.loading = true
|
||||
let result: 'ok' | 'empty' | 'aborted' | 'error' = 'error'
|
||||
try {
|
||||
// A failed load is reported by the summary request, which needs it too.
|
||||
await this.sessionAiTarget().catch(() => {})
|
||||
this.#settleModel()
|
||||
// Everything is the prefix, nothing is kept verbatim: keepFrom and
|
||||
// displayKeepFrom point past the end so the kept tail is empty.
|
||||
result = await this.runSummarization(
|
||||
@@ -3664,7 +3697,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
abortController,
|
||||
callbacks,
|
||||
get modelProvider() {
|
||||
return info ? resolveModelFor(info) : getCurrentModel()
|
||||
return info ? resolveModelFor(info, self.#modelPick) : getCurrentModel()
|
||||
},
|
||||
get webSearch() {
|
||||
return isWebSearchEnabledForProvider(this.modelProvider.provider, info)
|
||||
@@ -3997,6 +4030,10 @@ export class AIChatManager implements ChatViewHost {
|
||||
}
|
||||
|
||||
sendRequest = async (options: Parameters<typeof this.sendRequestImpl>[0] = {}) => {
|
||||
// Before any await, during which a pick in another session would move this one. Again once
|
||||
// the workspace is committed, which may not offer this model. Not while another tab runs the
|
||||
// session: storing the record here would overwrite what that tab stored.
|
||||
if (!this.runHeldElsewhere) this.#settleModel()
|
||||
if (this.#ready) {
|
||||
this.#sendsAwaitingReady++
|
||||
try {
|
||||
@@ -4552,6 +4589,7 @@ export class AIChatManager implements ChatViewHost {
|
||||
// loading + abortController were set optimistically before beforeSend, above.
|
||||
this.#automaticScroll = true
|
||||
|
||||
this.#settleModel()
|
||||
const model = this.currentModel
|
||||
if (model) {
|
||||
const chatId = this.historyManager.getCurrentChatId()
|
||||
|
||||
@@ -1,21 +1,15 @@
|
||||
<script lang="ts">
|
||||
/**
|
||||
* The session chat's model button: a fixed ChatModelSettings config over the copilot's
|
||||
* own state — the workspace's configured models, the session's model/effort selection
|
||||
* and its localStorage pins, the custom-prompt editors, and the free-tier grant.
|
||||
* own state — the workspace's configured models, the session's model/effort selection,
|
||||
* the custom-prompt editors, and the free-tier grant.
|
||||
*/
|
||||
import { User, Building2, Settings, ExternalLink } from 'lucide-svelte'
|
||||
import ChatModelSettings from '../ChatModelSettings.svelte'
|
||||
import { carriedReasoning, type ChatModelSettingsConfig } from '../chatModelSettings'
|
||||
import {
|
||||
COPILOT_SESSION_MODEL_SETTING_NAME,
|
||||
COPILOT_SESSION_PROVIDER_SETTING_NAME,
|
||||
COPILOT_SESSION_REASONING_SETTING_NAME
|
||||
} from '$lib/stores'
|
||||
import { storeLocalSetting, type Item } from '$lib/utils'
|
||||
import type { Item } from '$lib/utils'
|
||||
import {
|
||||
applySavedWorkspaceCopilotInfo,
|
||||
copilotSessionModel,
|
||||
getUserCustomPrompts,
|
||||
setUserCustomPrompts
|
||||
} from '$lib/aiStore'
|
||||
@@ -71,23 +65,16 @@
|
||||
REASONING_OFF,
|
||||
getReasoningCapability(m.provider, m.model)
|
||||
)
|
||||
$copilotSessionModel = { ...m, ...(keep !== undefined ? { reasoning: keep } : {}) }
|
||||
storeLocalSetting(COPILOT_SESSION_MODEL_SETTING_NAME, m.model)
|
||||
storeLocalSetting(COPILOT_SESSION_PROVIDER_SETTING_NAME, m.provider)
|
||||
storeLocalSetting(COPILOT_SESSION_REASONING_SETTING_NAME, keep)
|
||||
aiChatManager.pickModel({ ...m, ...(keep !== undefined ? { reasoning: keep } : {}) })
|
||||
}
|
||||
|
||||
function selectReasoning(value: string) {
|
||||
const reasoning = value === REASONING_OFF ? REASONING_OFF : value
|
||||
$copilotSessionModel = {
|
||||
// With the model, so the reasoning choice persists with it.
|
||||
aiChatManager.pickModel({
|
||||
...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)
|
||||
reasoning: value
|
||||
})
|
||||
}
|
||||
|
||||
// ---- prompt parameters (User / Workspace custom prompts) ----
|
||||
|
||||
@@ -17,14 +17,12 @@
|
||||
type ReasoningProviderModel
|
||||
} from '../reasoningRegistry'
|
||||
|
||||
let providerModel = $derived.by(() => {
|
||||
// Subscribes only: `tryResolveModelFor` reads the pick through `get()`, which tracks nothing.
|
||||
void $copilotSessionModel
|
||||
return (tryResolveModelFor($copilotInfo) ?? {
|
||||
let providerModel = $derived(
|
||||
(tryResolveModelFor($copilotInfo, $copilotSessionModel) ?? {
|
||||
model: 'No model',
|
||||
provider: 'No provider'
|
||||
}) as ReasoningProviderModel
|
||||
})
|
||||
)
|
||||
|
||||
let multipleModels = $derived($copilotInfo.aiModels.length > 1)
|
||||
|
||||
|
||||
@@ -899,9 +899,10 @@ export function modelSupportsWebSearch(provider: AIProvider | undefined, model:
|
||||
return providerSupportsWebSearch(provider)
|
||||
}
|
||||
|
||||
/** The model a request sends: for `info`'s workspace when given, else the tab's. */
|
||||
/** The model a request that names none sends: `info`'s workspace's default when given, else the
|
||||
* tab's. */
|
||||
function modelFor(info: CopilotInfo | undefined): AIProviderModel {
|
||||
return info ? resolveModelFor(info) : getCurrentModel()
|
||||
return info ? resolveModelFor(info, undefined) : getCurrentModel()
|
||||
}
|
||||
|
||||
export function getProviderAndCompletionConfig<K extends boolean>({
|
||||
@@ -1223,9 +1224,9 @@ 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?: { maxTokensCap?: number; workspace?: string; info?: CopilotInfo }
|
||||
options?: Partial<AiTarget> & { maxTokensCap?: number; forceModelProvider?: AIProviderModel }
|
||||
): Promise<string> {
|
||||
const modelProvider = modelFor(options?.info)
|
||||
const modelProvider = options?.forceModelProvider ?? modelFor(options?.info)
|
||||
const drain = async (forceCompletions: boolean) => {
|
||||
const stream = await getCompletion(messages, abortController, undefined, {
|
||||
forceCompletions,
|
||||
|
||||
@@ -44,9 +44,11 @@
|
||||
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
|
||||
}
|
||||
|
||||
let { scope, source, onPost, info }: Props = $props()
|
||||
let { scope, source, onPost, info, defaultModel }: Props = $props()
|
||||
|
||||
let items = $derived(scopeItems(scope))
|
||||
let workspaceId = $derived(scopeWorkspace(scope))
|
||||
@@ -73,10 +75,9 @@
|
||||
// which is only the default until something is picked.
|
||||
let pickedModelKey = $state<string | undefined>(undefined)
|
||||
let aiModels = $derived((info ?? $copilotInfo).aiModels)
|
||||
let chatModel = $derived.by(() => {
|
||||
void $copilotSessionModel
|
||||
return tryResolveModelFor(info ?? $copilotInfo)
|
||||
})
|
||||
let chatModel = $derived(
|
||||
defaultModel ?? tryResolveModelFor(info ?? $copilotInfo, $copilotSessionModel)
|
||||
)
|
||||
let selectedModelKey = $derived(pickedModelKey ?? (chatModel && modelKey(chatModel)))
|
||||
|
||||
async function run() {
|
||||
|
||||
@@ -186,7 +186,7 @@ export async function reviewChanges(
|
||||
scope: ReviewScope,
|
||||
abortController: AbortController,
|
||||
options?: {
|
||||
/** Defaults to the chat's current model. */
|
||||
/** Defaults to the workspace default of `info`, or without it to the last pick. */
|
||||
model?: AIProviderModel
|
||||
/** The reviewed workspace's AI config, when it is not the tab's. */
|
||||
info?: CopilotInfo
|
||||
|
||||
@@ -37,12 +37,22 @@
|
||||
import { truncate } from '$lib/utils'
|
||||
import Toggle from '$lib/components/Toggle.svelte'
|
||||
import { loadWorkspaceCopilotInfo } from '$lib/aiStore'
|
||||
import { Archive, ArchiveRestore, EllipsisVertical, GitFork, Pencil, Trash2 } from 'lucide-svelte'
|
||||
import CloseButton from '$lib/components/common/CloseButton.svelte'
|
||||
import {
|
||||
AlertTriangle,
|
||||
Archive,
|
||||
ArchiveRestore,
|
||||
EllipsisVertical,
|
||||
GitFork,
|
||||
Pencil,
|
||||
Trash2
|
||||
} from 'lucide-svelte'
|
||||
import SessionChangesBar from './SessionChangesBar.svelte'
|
||||
import { sessionHandEdits } from './sessionHandEdits.svelte'
|
||||
import SessionShareButton from './SessionShareButton.svelte'
|
||||
import {
|
||||
deleteSessionsForWorkspace,
|
||||
dismissReplacedModel,
|
||||
getEffectiveWorkspaceId,
|
||||
moveSessionToNewFork,
|
||||
moveSessionToWorkspace,
|
||||
@@ -631,11 +641,32 @@
|
||||
{#snippet sessionEmptyHint()}<div class="flex-1 min-h-0"></div>{/snippet}
|
||||
|
||||
{#snippet inputPreface()}
|
||||
<!-- gap-1 (4px) spaces the archived banner and the changes bar when both
|
||||
<!-- gap-1 (4px) spaces the banners and the changes bar when several
|
||||
are visible. Each renders a single in-flow root (or nothing); the diff
|
||||
drawer is position:fixed, so it doesn't count as a flex item — no stray
|
||||
gap when only one shows. -->
|
||||
<div class="flex flex-col gap-1">
|
||||
{#if session.replacedModel && session.model}
|
||||
{@const replaced = session.replacedModel}
|
||||
{@const current = session.model}
|
||||
<!-- Two providers can offer a model of the same name. -->
|
||||
{@const sameName = replaced.model === current.model}
|
||||
<div class="{bannerClass} bg-surface-tertiary" role="status">
|
||||
<div class="flex flex-row items-center gap-2 min-w-0">
|
||||
<AlertTriangle class="w-4 h-4 shrink-0 text-tertiary" />
|
||||
<span class="text-primary min-w-0 break-words">
|
||||
{replaced.model}{sameName ? ` (${replaced.provider})` : ''} is not available here. This
|
||||
session now uses {current.model}{sameName ? ` (${current.provider})` : ''}.
|
||||
</span>
|
||||
</div>
|
||||
<CloseButton
|
||||
small
|
||||
noBg
|
||||
title="Dismiss"
|
||||
onClick={() => dismissReplacedModel(session.id)}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
{#if session.archived && !isUnavailable}
|
||||
<!-- Unarchive is only meaningful when the workspace is still live:
|
||||
putSession refuses to resurrect a session whose workspace is gone,
|
||||
|
||||
@@ -43,6 +43,7 @@
|
||||
import type { SessionDeployModel, DiffValues } from './sessionDeployModel.svelte'
|
||||
import { SIDE_BY_SIDE_MIN_WIDTH } from '$lib/components/diffEditorTypes'
|
||||
import { getWorkspaceCopilotInfo } from '$lib/aiStore'
|
||||
import { getAiChatManager } from '$lib/components/copilot/chat/aiChatManagerContext'
|
||||
import AiReview from '$lib/components/deploymentRequest/AiReview.svelte'
|
||||
import type { ReviewItem } from '$lib/components/deploymentRequest/aiReview'
|
||||
|
||||
@@ -96,6 +97,7 @@
|
||||
const reviewAiInfo = $derived(
|
||||
reviewWorkspaceId ? getWorkspaceCopilotInfo(reviewWorkspaceId) : undefined
|
||||
)
|
||||
const aiChat = getAiChatManager()
|
||||
|
||||
let drawer: Drawer | undefined = $state(undefined)
|
||||
let searchQuery = $state('')
|
||||
@@ -1168,6 +1170,7 @@
|
||||
scope={{ kind: 'drafts', workspaceId: reviewWorkspaceId, items: reviewItems }}
|
||||
source="session_edits"
|
||||
info={reviewAiInfo}
|
||||
defaultModel={aiChat.isSessionChat ? aiChat.currentModel : undefined}
|
||||
/>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import type { AIConfig } from '$lib/gen'
|
||||
import { copilotSessionModel, invalidateWorkspaceCopilotInfo } from '$lib/aiStore'
|
||||
import { workspaceStore } from '$lib/stores'
|
||||
import { createSession, sessionState, type Session } from './sessionState.svelte'
|
||||
import { getOrCreateRuntime } from './sessionRuntime.svelte'
|
||||
|
||||
const mocks = vi.hoisted(() => ({ config: {} as any }))
|
||||
vi.mock('$lib/utils/featureUsage', () => ({ logFeatureUsage: vi.fn() }))
|
||||
vi.mock('monaco-editor', () => ({ Selection: class Selection {} }))
|
||||
vi.mock('$lib/gen', async (importOriginal) => {
|
||||
const gen = await importOriginal<typeof import('$lib/gen')>()
|
||||
return {
|
||||
...gen,
|
||||
WorkspaceService: Object.assign(Object.create(gen.WorkspaceService), {
|
||||
getCopilotInfo: async () => mocks.config
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
const X = { provider: 'mistral' as const, model: 'model-x' }
|
||||
const Y = { provider: 'mistral' as const, model: 'model-y' }
|
||||
|
||||
function offer(...models: string[]) {
|
||||
mocks.config = {
|
||||
providers: { mistral: { resource_path: 'u/admin/m', models } },
|
||||
default_model: { provider: 'mistral', model: 'model-x' }
|
||||
} satisfies AIConfig
|
||||
invalidateWorkspaceCopilotInfo()
|
||||
}
|
||||
|
||||
let sent: string[] = []
|
||||
let nextId = 0
|
||||
function startedSession() {
|
||||
const session = { id: `s${nextId++}`, summary: 's', workspace_id: 'ws', createdAt: 0 }
|
||||
sessionState.sessions = [...sessionState.sessions, session as Session]
|
||||
const manager = getOrCreateRuntime(session as Session).manager
|
||||
const record = () => sessionState.sessions.find((s) => s.id === session.id)
|
||||
return { manager, record }
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
sent = []
|
||||
sessionState.sessions = []
|
||||
copilotSessionModel.set(undefined)
|
||||
workspaceStore.set('ws')
|
||||
offer('model-x', 'model-y')
|
||||
vi.stubGlobal('fetch', async (input: RequestInfo | URL, init?: RequestInit) => {
|
||||
const url = input instanceof Request ? input.url : String(input)
|
||||
if (!url.includes('/ai/proxy/')) return Response.json([])
|
||||
const body = JSON.parse(String(init?.body ?? '{}'))
|
||||
sent.push(body.model)
|
||||
const chunk = (delta: object, finish_reason: string | null) =>
|
||||
`data: ${JSON.stringify({ id: 'c', object: 'chat.completion.chunk', created: 0, model: body.model, choices: [{ index: 0, delta, finish_reason }] })}\n\n`
|
||||
return new Response(
|
||||
chunk({ content: '<summary>ok</summary>' }, null) + chunk({}, 'stop') + 'data: [DONE]\n\n',
|
||||
{ headers: { 'content-type': 'text/event-stream' } }
|
||||
)
|
||||
})
|
||||
})
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
it('a send keeps the model it was pressed on while the history loads', async () => {
|
||||
const a = startedSession()
|
||||
const b = startedSession()
|
||||
await a.manager.sessionAiTarget()
|
||||
let restored = () => {}
|
||||
a.manager.setReadyGate(new Promise<void>((r) => (restored = r)))
|
||||
const turn = a.manager.sendRequest({ instructions: 'hi' })
|
||||
b.manager.pickModel(Y)
|
||||
restored()
|
||||
await turn
|
||||
expect(sent).toEqual(['model-x'])
|
||||
expect(a.record()?.model).toMatchObject(X)
|
||||
})
|
||||
|
||||
it('a session sends and compacts with its own pick', async () => {
|
||||
const a = startedSession()
|
||||
const b = startedSession()
|
||||
// Not the workspace default, which a request that loses the pick would fall back to.
|
||||
a.manager.pickModel({ ...Y, reasoning: 'high' })
|
||||
b.manager.pickModel({ ...X, reasoning: 'low' })
|
||||
await a.manager.sendRequest({ instructions: 'hi' })
|
||||
await a.manager.sendRequest({ instructions: 'again' })
|
||||
await a.manager.compactManually()
|
||||
expect(sent).toEqual(['model-y', 'model-y', 'model-y'])
|
||||
expect(a.manager.currentModel).toEqual({ ...Y, reasoning: 'high' })
|
||||
})
|
||||
|
||||
it('a pick its workspace no longer offers is replaced for good, and said so', async () => {
|
||||
const a = startedSession()
|
||||
a.manager.pickModel(Y)
|
||||
await a.manager.sessionAiTarget()
|
||||
// Only once the send is prepared, as when it commits a workspace that does not offer the pick.
|
||||
const beforeSend = a.manager.beforeSend
|
||||
a.manager.beforeSend = async () => {
|
||||
await beforeSend?.()
|
||||
offer('model-x')
|
||||
}
|
||||
await a.manager.sendRequest({ instructions: 'hi' })
|
||||
a.manager.beforeSend = beforeSend
|
||||
|
||||
expect(sent[0]).toBe('model-x')
|
||||
offer('model-x', 'model-y')
|
||||
await a.manager.sendRequest({ instructions: 'again' })
|
||||
expect(sent).toEqual(['model-x', 'model-x'])
|
||||
// Later sends keep the notice; a pick ends it.
|
||||
expect(a.record()?.replacedModel).toMatchObject(Y)
|
||||
a.manager.pickModel(Y)
|
||||
expect(a.record()?.replacedModel).toBeUndefined()
|
||||
})
|
||||
|
||||
it('compacting also replaces a pick its workspace no longer offers', async () => {
|
||||
const a = startedSession()
|
||||
a.manager.pickModel(Y)
|
||||
await a.manager.sendRequest({ instructions: 'hi' })
|
||||
offer('model-x')
|
||||
await a.manager.compactManually()
|
||||
|
||||
expect(sent.at(-1)).toBe('model-x')
|
||||
expect(a.record()?.model).toMatchObject(X)
|
||||
})
|
||||
|
||||
it('an untouched draft follows the last pick', async () => {
|
||||
const draft = getOrCreateRuntime(createSession()).manager
|
||||
const a = startedSession()
|
||||
await draft.sessionAiTarget()
|
||||
draft.pickModel(X)
|
||||
a.manager.pickModel(Y)
|
||||
expect(draft.currentModel).toMatchObject(Y)
|
||||
})
|
||||
@@ -50,9 +50,11 @@ import {
|
||||
getEffectiveWorkspaceId,
|
||||
markSessionStateChanged,
|
||||
materializeTransient,
|
||||
pickSessionModel,
|
||||
sessionState,
|
||||
setGeneratedSessionSummary,
|
||||
setSessionChatId,
|
||||
setSessionModel,
|
||||
setSessionPreviewCollapsed,
|
||||
setSessionPreviewSize,
|
||||
setSessionTabs,
|
||||
@@ -392,6 +394,9 @@ function createRuntime(session: Session): SessionRuntime {
|
||||
manager.sessionId = session.id
|
||||
manager.workMode = session.workMode ?? AIWorkMode.BUILD
|
||||
manager.onWorkModeChanged = (mode) => setSessionWorkMode(session.id, mode)
|
||||
manager.modelPickResolver = () => sessionState.sessions.find((x) => x.id === session.id)?.model
|
||||
manager.onModelPicked = (model) => pickSessionModel(session.id, model)
|
||||
manager.onModelSettled = (model, replaced) => setSessionModel(session.id, model, replaced)
|
||||
manager.directInResolver = () => sessionState.sessions.find((x) => x.id === session.id)?.direct_in
|
||||
manager.workingInResolver = () => {
|
||||
const s = sessionState.sessions.find((x) => x.id === session.id)
|
||||
|
||||
@@ -15,6 +15,7 @@ import { getLocalSetting, storeLocalSetting } from '$lib/utils'
|
||||
import { logFeatureUsage } from '$lib/utils/featureUsage'
|
||||
import { isReadOnlySessionWorkspace } from '../copilot/chat/global/sessionAccess'
|
||||
import { AIWorkMode } from '../copilot/chat/workMode'
|
||||
import type { ReasoningProviderModel } from '../copilot/reasoningRegistry'
|
||||
import { workspaceRootId } from './sessionScope.svelte'
|
||||
import { type DBSchema, type IDBPDatabase } from 'idb'
|
||||
import { userScopedDb } from '$lib/userScopedDb'
|
||||
@@ -184,6 +185,12 @@ export type Session = {
|
||||
workingIn?: string[]
|
||||
// How the scope was set, for its usage counter. Absent: the default.
|
||||
workingInSource?: 'preset' | 'manual'
|
||||
// Absent until a pick or the next send, and the session then follows the last pick: unsent,
|
||||
// stored before this field, or restored from the backup. Per browser, like workMode.
|
||||
model?: ReasoningProviderModel
|
||||
// The pick `model` stands in for because the workspace does not offer it, until the user
|
||||
// dismisses the notice or picks a model.
|
||||
replacedModel?: ReasoningProviderModel
|
||||
// Unsent composer text for a pending (uncommitted) session, persisted with
|
||||
// the record so each parallel draft restores its own typed-but-unsent prompt.
|
||||
// Only tracked while unsent; cleared once the workspace commits at first send.
|
||||
@@ -1491,6 +1498,35 @@ export function setSessionWorkMode(id: string, mode: AIWorkMode): void {
|
||||
persistTouched(s)
|
||||
}
|
||||
|
||||
/** Not a touch: picking a model on Home's untouched draft must not keep it in the sidebar. */
|
||||
export function setSessionModel(
|
||||
id: string,
|
||||
model: ReasoningProviderModel,
|
||||
replaced?: ReasoningProviderModel
|
||||
): void {
|
||||
const s = sessionState.sessions.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
s.model = { ...model }
|
||||
s.replacedModel = replaced
|
||||
if (!s.transient) void putSession(s)
|
||||
}
|
||||
|
||||
export function dismissReplacedModel(id: string): void {
|
||||
const s = sessionState.sessions.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
delete s.replacedModel
|
||||
void putSession(s)
|
||||
}
|
||||
|
||||
/** A pick by the user, which is also the last pick: an untouched draft follows that one, so it
|
||||
* drops a pick of its own. */
|
||||
export function pickSessionModel(id: string, model: ReasoningProviderModel): void {
|
||||
for (const s of sessionState.sessions) {
|
||||
if (s.id !== id && isDiscardableDraft(s)) delete s.model
|
||||
}
|
||||
setSessionModel(id, model)
|
||||
}
|
||||
|
||||
/** Not a touch: picking a scope on Home's untouched draft must not keep it in the sidebar. */
|
||||
export function setSessionWorkingIn(
|
||||
id: string,
|
||||
|
||||
Reference in New Issue
Block a user