fix(session): save default model settings in the background

This commit is contained in:
Yichen Jiang committed 2026-09-24 19:48:49 +08:00
1 parent c8631b2064
commit 86331673d9
18 files changed
+136 -29

No files matched your search

+20 -1
View File
@@ -107,7 +107,24 @@ describe('web e2e: the composer model switch is the default for later sessions',
expect(await trigger.evaluate(element => getComputedStyle(element).fontWeight)).toBe('400')
await trigger.click()
await page.getByRole('menuitem', { name: /模型/ }).click()
await page.getByRole('menuitemradio', { name: 'Acme Large' }).click()
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const blocked = scaffold.ctx.hmr.runExclusive(async () => {
entered.resolve(undefined)
await release.promise
})
try {
await entered.promise
await page.getByRole('menuitemradio', { name: 'Acme Large' }).click()
await expect.poll(() => trigger.getAttribute('aria-busy')).toBe('false')
await expect.poll(() => trigger.textContent()).toContain('Acme Large')
expect(scaffold.ctx.agentDefaultModel.currentSelection()).toEqual({ provider: START_ROUTE, model: START_MODEL })
const aria = await captureStableAria(page, '[data-composer-card]', scaffold.workspaceCwd)
await compareOrRefreshGolden(fileURLToPath(new URL('./expected/default-model/background-save.expected.md', import.meta.url)), aria, webSnapshotMode())
} finally {
release.resolve(undefined)
await blocked
}
// The switch is what sets the default: the shared Agent-route settings section
// now names it, beside the provider profiles the Models page writes.
@@ -119,6 +136,8 @@ describe('web e2e: the composer model switch is the default for later sessions',
expect(document).toContain(`provider: ${ROUTE}`)
expect(document).toContain(`model: ${MODEL}`)
await expect.poll(() => scaffold.ctx.agentDefaultModel.currentSelection())
.toEqual({ provider: ROUTE, model: MODEL })
// A session created after the switch starts from it...
expect(await currentOf(await createSession('default-model-after')))
.toEqual({ provider: ROUTE, model: MODEL })
@@ -0,0 +1,5 @@
- textbox "描述你想要构建的内容, / 调用指令, @ 文件或对话"
- button "添加文件或调用指令"
- button "访问模式,当前:工作区内修改": 工作区内修改
- button "选择模型,当前 Acme Large": Acme Large
- button "发送消息" [disabled]
+2 -1
View File
@@ -432,7 +432,8 @@ currentSelection(): ModelSelection
/**
* Save the complete default model selection. A deployment without a configuration
* editor keeps its composition entry.
* editor keeps its composition entry. Saves commit in submission order; a failed
* save rejects its caller without blocking later saves.
* @param next - resolved selection accepted by an entry point.
* @returns fulfillment after the optional profile write settles.
*/
+2 -1
View File
@@ -442,7 +442,8 @@ currentSelection(): ModelSelection
/**
* Save the complete default model selection. A deployment without a configuration
* editor keeps its composition entry.
* editor keeps its composition entry. Saves commit in submission order; a failed
* save rejects its caller without blocking later saves.
* @param next - resolved selection accepted by an entry point.
* @returns fulfillment after the optional profile write settles.
*/
+2 -2
View File
@@ -820,9 +820,9 @@ inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise<SessionInspectio
@Remote('create') create(request: SessionCreateRequest): Promise<SessionCreateValue>
/**
* Select one Session-local model after explicitly resuming the Session.
* Select one Session-local model after explicitly resuming the Session; save the default in the background.
* @param request - Session identity and requested model selection.
* @returns the normalized selection installed for the Session.
* @returns the normalized selection installed for the Session, without waiting for default persistence.
*/
@Remote('selectModel') selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue>
+2 -2
View File
@@ -824,9 +824,9 @@ inspect( sessionId: SessionId, signal?: AbortSignal, ): Promise<SessionInspectio
@Remote('create') create(request: SessionCreateRequest): Promise<SessionCreateValue>
/**
* Select one Session-local model after explicitly resuming the Session.
* Select one Session-local model after explicitly resuming the Session; save the default in the background.
* @param request - Session identity and requested model selection.
* @returns the normalized selection installed for the Session.
* @returns the normalized selection installed for the Session, without waiting for default persistence.
*/
@Remote('selectModel') selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue>
@@ -21,8 +21,8 @@
en: 41bdda1ac32df558
zh: aa5d0e325924066b
/session-controller/session-media-references:
en: c7e6bbb57a4894b7
zh: f66d79776a7e33ec
en: 266ab2b1e2fec542
zh: b3450ae28a1e0baf
/session-controller/configuration:
en: 5c4c4224074e38a8
zh: e0b0edac65c88ff4
@@ -80,6 +80,8 @@ References keep local Session data, scoped Contexts, and history streams alive,
GUI model selection requires the exact provider/model pair in the available catalog; unavailable choices reject with `session/model-unavailable`. Prompt admission retains the saved route without a catalog availability gate, so request execution reports missing credentials or unavailable models. `initializeDefaultModel()` saves the first available account model after login when no other provider has a configured API key; credential checks use configured references independently of model availability. A provider with no available models rejects initialization with `session/provider-models-unavailable`. Availability never substitutes another model or rewrites a Session selection.
A successful `selectModel` response acknowledges the Session-local selection without waiting for the default profile setting to save. Default saves run in the background in submission order; a failure logs a warning and leaves the Session selection intact. New Sessions read the last successfully saved default.
-----
<a id="configuration"></a>
@@ -80,6 +80,8 @@ Client 的首次 `follow`、重连首屏与 `loadOlder()` 至少请求 50 条以
GUI 模型选择要求确切提供方/模型对出现在可用目录中;不可用的选择以 `session/model-unavailable` 拒绝。提示词准入保留已保存的路由,不按目录可用性阻断发送,由请求执行报告凭据缺失或模型不可用。`initializeDefaultModel()` 在账号登录后、其他提供方均未配置 API key 时,将第一个可用账号模型保存为默认模型;凭据检查使用已配置的引用,不依赖模型是否可用。提供方没有可用模型时,初始化以 `session/provider-models-unavailable` 拒绝。可用性变化不会替换模型或改写会话选择。
`selectModel` 成功返回表示会话级模型选择已生效,不等待默认 profile 设置保存。默认设置在后台按提交顺序保存;保存失败会记录警告,并保留会话选择。新会话读取最近一次成功保存的默认值。
-----
<a id="configuration"></a>
@@ -144,9 +144,9 @@ export class SessionCommandController {
}
/**
* Validate and install one Session-local model selection.
* Validate and install one Session-local model selection; save the default in the background.
* @param request - Session identity and requested model selection.
* @returns the normalized selection installed for the Session.
* @returns the normalized selection installed for the Session, without waiting for default persistence.
*/
async selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
const agent = await this.resolveAgent(request.sessionId)
@@ -168,13 +168,11 @@ export class SessionCommandController {
: { reasoningEffort: resolved.reasoningEffort }),
}
this.agents.selectForNextRequest(agent, selected)
try {
await this.ctx.agentDefaultModel.saveSelection(selected)
} catch (error) {
void this.ctx.agentDefaultModel.saveSelection(selected).catch((error: unknown) => {
this.ctx.logger.warn(
`session-controller: model selection changed for the Session but the default was not saved: ${String(error)}`,
)
}
})
return { selected: { ...selected } }
} catch (error) {
if (remoteErrorOf(error) !== undefined) throw error
+2 -2
View File
@@ -275,9 +275,9 @@ export class SessionController extends TypertRemoteService {
}
/**
* Select one Session-local model after explicitly resuming the Session.
* Select one Session-local model after explicitly resuming the Session; save the default in the background.
* @param request - Session identity and requested model selection.
* @returns the normalized selection installed for the Session.
* @returns the normalized selection installed for the Session, without waiting for default persistence.
*/
@Remote('selectModel')
selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue> {
@@ -5,7 +5,7 @@
* boundary for a running selection change.
*/
import { describe, expect, it, vi } from 'vitest'
import { describe, expect, it, vi, onTestFinished } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import AgentRegistry, { agentEvents } from '@deepseek-ai/dsh-agent'
import type { Agent } from '@deepseek-ai/dsh-agent'
@@ -617,8 +617,40 @@ describe('Web session model selection', () => {
await ctx.fiber.dispose()
})
it('accepts consecutive model switches while default persistence is blocked', async () => {
const { ctx, sessionId } = await harness()
const release = Promise.withResolvers<undefined>()
const saves: Promise<void>[] = []
const operations: Promise<unknown>[] = []
onTestFinished(async () => {
release.resolve(undefined)
await Promise.allSettled([...operations, ...saves])
await ctx.fiber.dispose()
})
const remote = createSessionTestRemote(ctx, {
defaultModelSelection: () => ({ provider: 'deepseek-official', model: 'deepseek-chat' }),
saveDefaultModelSelection: () => {
saves.push(release.promise)
return release.promise
},
cwd: '/tmp',
})
for (const model of ['deepseek-reasoner', 'deepseek-chat']) {
let returned = false
const operation = remote.selectModel({ sessionId, provider: 'deepseek-official', model })
.then((result) => { expectValue(result); returned = true })
operations.push(operation)
await expect.poll(() => returned).toBe(true)
expect(currentSelection(ctx, sessionId)).toMatchObject({ provider: 'deepseek-official', model })
}
expect(saves).toHaveLength(2)
})
it('saves an accepted selection as the default and survives a storage failure', async () => {
const { ctx, sessionId } = await harness()
const warn = vi.spyOn(ctx.logger, 'warn').mockImplementation(() => {})
onTestFinished(() => { warn.mockRestore() })
const saved: unknown[] = []
let reject = false
const remote = createSessionTestRemote(ctx, {
@@ -650,6 +682,9 @@ describe('Web session model selection', () => {
expect(stillAccepted.selected).toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' })
expect(currentSelection(ctx, sessionId))
.toEqual({ provider: 'deepseek-official', model: 'deepseek-chat', reasoningEffort: 'high' })
await expect.poll(() => warn.mock.calls).toContainEqual([
'session-controller: model selection changed for the Session but the default was not saved: Error: read-only document',
])
await ctx.fiber.dispose()
})
@@ -27,8 +27,8 @@
en: 592af7e68423bd1c
zh: a509b637f2a14687
/deepseek-ai-dsh-agent-default-model/understand-the-implementation/design-concept:
en: 3459310298508557
zh: 1bce84eba76d6531
en: 9ff35825ebe9200d
zh: 613ebd35df840aea
/deepseek-ai-dsh-agent-default-model/understand-the-implementation/source-map:
en: 68c75c85685bb265
zh: f3c50b3078d1500e
+1 -1
View File
@@ -68,7 +68,7 @@ This section explains how the service realizes the behavior above; the observabl
### Design concept
The service retains its validated Config references and samples them in `currentSelection()`. `saveSelection()` delegates a complete selection to the profile configuration editor. Session-specific selection takes precedence in the consumer.
The service retains its validated Config references and samples them in `currentSelection()`. `saveSelection()` captures the submitted values and serializes profile writes in submission order, including overlapping callers. Each caller observes its own write failure; a rejected write does not prevent later saves. Session-specific selection takes precedence in the consumer.
### Source map
@@ -68,7 +68,7 @@ await ctx.agentDefaultModel.saveSelection({ provider, model, reasoningEffort: 'h
### 设计理念
此服务保留已验证的 Config 引用,并在 `currentSelection()` 中读取。`saveSelection()` 将完整选择交给 profile 配置编辑器。消费者优先使用会话级选择。
此服务保留已验证的 Config 引用,并在 `currentSelection()` 中读取。`saveSelection()` 捕获提交值,并按提交顺序串行写入 profile,包括调用重叠的情况。每个调用方收到各自的写入失败;一次写入被拒绝不会阻止后续保存。消费者优先使用会话级选择。
### 源码地图
+11 -3
View File
@@ -46,6 +46,8 @@ function selection(settings: { provider: string; model: string; reasoningEffort?
* Each operation reads the owning Config references.
*/
export class AgentDefaultModelConfig extends Service {
private saves: Promise<void> = Promise.resolve()
static Config = z.object({
provider: z.string().required().volatile(),
model: z.string().required().volatile(),
@@ -72,17 +74,23 @@ export class AgentDefaultModelConfig extends Service {
/**
* Save the complete default model selection. A deployment without a configuration
* editor keeps its composition entry.
* editor keeps its composition entry. Saves commit in submission order; a failed
* save rejects its caller without blocking later saves.
* @param next - resolved selection accepted by an entry point.
* @returns fulfillment after the optional profile write settles.
*/
async saveSelection(next: ModelSelection): Promise<void> {
const entry = this.ownerContext.fiber.entry
if (entry === undefined) return
await this.ctx.get('configEditor')?.edit(entry, () => ({
const editor = this.ctx.get('configEditor')
if (editor === undefined) return
const config = {
provider: next.provider, model: next.model,
...next.reasoningEffort === undefined ? {} : { reasoningEffort: String(next.reasoningEffort) },
}))
}
const saved = this.saves.then(() => editor.edit(entry, () => config))
this.saves = saved.catch(() => {})
await saved
}
}
@@ -1,6 +1,6 @@
/** Default model references remain live without a settings service. */
import { Context } from '@deepseek-ai/cordis'
import { expect, it, onTestFinished } from 'vitest'
import { expect, it, onTestFinished, vi } from 'vitest'
import DefaultModel from '../src/index.ts'
import { liveConfig } from '../../../settings/settings/tests/live-config.ts'
@@ -31,3 +31,39 @@ it('persists complete selections through its owning profile entry', async () =>
await standalone.agentDefaultModel.saveSelection({ provider: 'test', model: 'ignored' })
expect(standalone.agentDefaultModel.currentSelection().model).toBe('original')
})
it('serializes overlapping saves and continues after a rejected write', async () => {
const { configurationFixture } = await import('../../../settings/settings/tests/configuration-fixture.ts')
const { ctx } = await configurationFixture({ hmr: false })
const entered = Promise.withResolvers<undefined>()
const release = Promise.withResolvers<undefined>()
const editor = ctx.configEditor
const edit = editor.edit.bind(editor)
const calls: string[] = []
const intercepted = vi.spyOn(editor, 'edit').mockImplementationOnce(async () => {
calls.push('rejected')
entered.resolve(undefined)
await release.promise
throw new Error('read-only document')
}).mockImplementation(async (entry, change) => {
calls.push('saved')
await edit(entry, change)
})
const first = ctx.agentDefaultModel.saveSelection({ provider: 'test', model: 'rejected' })
const failed = expect(first).rejects.toThrow('read-only document')
const lastSelection = { provider: 'test', model: 'final' }
const last = ctx.agentDefaultModel.saveSelection(lastSelection)
onTestFinished(async () => {
release.resolve(undefined)
await Promise.allSettled([failed, last])
intercepted.mockRestore()
})
lastSelection.model = 'mutated'
await entered.promise
expect(calls).toEqual(['rejected'])
release.resolve(undefined)
await failed
await last
expect(calls).toEqual(['rejected', 'saved'])
expect(ctx.agentDefaultModel.currentSelection()).toEqual({ provider: 'test', model: 'final' })
})
@@ -94,7 +94,7 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: 'async saveSelection(next: ModelSelection): Promise<void>',
description: 'Save the complete default model selection. A deployment without a configuration editor keeps its composition entry.',
description: 'Save the complete default model selection. A deployment without a configuration editor keeps its composition entry. Saves commit in submission order; a failed save rejects its caller without blocking later saves.',
parameters: [{ name: 'next', description: 'resolved selection accepted by an entry point.' }],
returns: 'fulfillment after the optional profile write settles.',
},
@@ -1889,9 +1889,9 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [
},
{
signature: '@Remote(\'selectModel\') selectModel(request: SessionSelectModelRequest): Promise<SessionSelectModelValue>',
description: 'Select one Session-local model after explicitly resuming the Session.',
description: 'Select one Session-local model after explicitly resuming the Session; save the default in the background.',
parameters: [{ name: 'request', description: 'Session identity and requested model selection.' }],
returns: 'the normalized selection installed for the Session.',
returns: 'the normalized selection installed for the Session, without waiting for default persistence.',
},
{
signature: '@Remote async initializeDefaultModel(): Promise<void>',