feat(ui): make a session that cannot send refuse to accept one

A default naming a route the Models page has since removed left the
composer saying 选择模型 while the input still accepted a message, which
then failed inside the adapter mid-turn.

`session.prompt` now refuses with `model-unavailable` before opening a
turn. That is the enforcement boundary: the method stays callable no
matter what a client disables. `session.models` reports the same fact as
`routable`, and ui-model pushes a block through the new
`ctx.conversation.blocks` registry so the bar renders the disabled
textarea it already renders without a workspace, carrying the blocker's
own reason. The push direction is forced — ui-model already depends on
ui-conversation, so ui-conversation cannot read it back.

The gate is `routable`, not "matches no advertised group": catalog
membership is advisory, so a route serving a model it stopped advertising
is missing from the groups yet perfectly usable, and `null` before the
first load never blocks so a slow Host cannot lock a working composer.

The scaffold gains a route-only adapter for fixture-less keyless
scenarios. Registering zero providers is a test artifact — every product
composition mounts one — and the goldens that froze the seat's fallback
label now show the model those scenarios actually route to.
This commit is contained in:
Yichen Jiang
2026-08-07 15:26:42 +08:00
parent 72618f29b5
commit bb43ff4f37
58 changed files with 859 additions and 163 deletions

View File

@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/ui-model/README.md
README.md: 5f9fc65939eb747d916fa5609423d3186d1fefde
README.zh.md: 3ed8db3095d96e48813cf5b15a206ebf4c894950
README.md: 5a6f998476629566d35af32efa5d8bc5072a872b
README.zh.md: 2bb22c55f1ae5af59f21e254804329d288806a90

View File

@@ -6,6 +6,8 @@ Model selection plugin, browser half: TWO entries over ONE per-session directory
The Host-reported provider/model/reasoning target is the single selection fact, but it is echoed only when the exact route remains in the advertised groups; removing that catalog row leaves the routable target intact while the trigger prompts `Select model`, no stale row is synthesized, and no Effort row is shown until the user picks an advertised model. Directory loads and selections share a generation counter so an older response never overwrites a newer one; a connection reset drops every resident projection and repulls the Host-restored target before display. Provider-local metadata failures list inline while usable groups stay selectable, and selection failures retain the prior target and directory.
When the Host reports that no adapter serves the session's route (`session.models.routable`), this plugin raises a composer block through `ctx.conversation.blocks` and the input goes inert with this plugin's own copy; recovering clears it without a reload. It follows `routable` and nothing else: a `null` — before the first load, or after one failed — never blocks, or a slow Host would lock a working composer, and catalog membership never blocks either, because a route serving a model it stopped advertising is missing from the groups yet perfectly usable. The trigger's own `Select model` fallback still covers that case, which is display, not a gate.
Directories are per-session, resolved lazily through `ctx.models.directoryFor(sessionId)`, and disposed with the session scope. Addressed subagent sessions expose neither entry, and their directory rejects loads, selections, and reconnect refreshes, because ordinary Agent-bound model RPCs would activate persisted child history outside the direct-parent continuation seam.
The `/client` export surface is the plugin body (`apply`/`inject`), `ModelService`, `ModelDirectory` with its state shape, and the seat's injected face type.

View File

@@ -6,6 +6,8 @@
Host 报告的提供方模型推理reasoning目标是唯一的选择事实但只有当该精确路由仍在已公布分组中时才会回显删除该目录行会保留仍可路由的目标但触发器会提示 `Select model`,系统不会合成陈旧行,且在用户选择已公布的模型之前不会显示 Effort 行。目录加载与选择共享一个代次计数器,旧响应不会覆盖新结果;连接重置会丢弃所有常驻目录投影,并在显示前重新拉取 Host 恢复的目标。各提供方的元数据获取失败会内联列出,同时可用分组仍可选择;选择失败会保留先前的目标和目录。
当宿主报告没有适配器服务该会话的路由(`session.models.routable`)时,本插件经 `ctx.conversation.blocks` 抬起一个编辑器 block输入框随之变为惰性并显示本插件自己的文案恢复后无需重新加载即自动清除。它只跟随 `routable``null`(首次加载之前,或加载失败之后)绝不阻断,否则一个慢的宿主就会锁死一个本来能用的编辑器;目录成员关系同样不阻断,因为一条仍在服务、只是不再公布该模型的路由不在分组里,却完全可用。触发器自己的 `Select model` 回退仍然覆盖那种情形——那是显示,不是闸门。
目录按会话惰性解析(`ctx.models.directoryFor(sessionId)`),随会话作用域一并释放。已寻址 subagent 会话不公开任一入口,其目录会拒绝加载、选择与重新连接刷新,因为绑定到 agent智能体的普通模型 RPC 会在直接 parent 继续执行 seam 之外激活持久化 child 历史。
`/client` 导出面为插件本体(`apply`/`inject`)、`ModelService``ModelDirectory` 及其状态形状、slot 注入面类型。

View File

@@ -15,6 +15,14 @@ import { createSnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
export interface ModelDirectoryState {
/** Target the host reports for the next assembled step; null before the first load. */
current: ModelTarget | null
/**
* Whether an adapter serves the current target's route, as the host reports
* it — null before the first load, which is NOT the same as blocked. Read
* this rather than "current matches no group": catalog membership is
* advisory, so a route serving a model it stopped advertising is missing
* from the groups yet perfectly usable.
*/
routable: boolean | null
/** Successfully loaded provider groups (last good load). */
groups: readonly ModelProviderGroup[]
/** Provider-local failures from the last load; usable groups stay usable. */
@@ -29,7 +37,7 @@ export interface ModelDirectoryState {
export class ModelDirectory {
/** The shared snapshot both entries render from (uSES-safe store). */
readonly store: SnapshotStore<ModelDirectoryState> = createSnapshotStore<ModelDirectoryState>({
current: null, groups: [], failures: [], status: 'idle', error: null,
current: null, routable: null, groups: [], failures: [], status: 'idle', error: null,
})
/** Latest operation wins; an older response never overwrites a newer one. */
@@ -65,9 +73,10 @@ export class ModelDirectory {
this.store.update((s) => { s.status = 'error'; s.error = `${result.error.code}: ${result.error.message}` })
throw new Error(`session.models failed: ${result.error.code}: ${result.error.message}`)
}
const { current, groups, failures } = result.value
const { current, routable, groups, failures } = result.value
this.store.update((s) => {
s.current = current
s.routable = routable
s.groups = groups
s.failures = failures
s.status = 'ready'
@@ -102,7 +111,14 @@ export class ModelDirectory {
this.store.update((s) => { s.status = 'error'; s.error = `${result.error.code}: ${result.error.message}` })
throw new Error(`session.selectModel failed: ${result.error.code}: ${result.error.message}`)
}
this.store.update((s) => { s.current = result.value.selected; s.status = 'ready'; s.error = null })
// The Host validated the route before accepting it, so a selection that
// landed is by construction one it can serve.
this.store.update((s) => {
s.current = result.value.selected
s.routable = true
s.status = 'ready'
s.error = null
})
}
/**
@@ -115,6 +131,7 @@ export class ModelDirectory {
++this.generation
this.store.update((s) => {
s.current = null
s.routable = null
s.groups = []
s.failures = []
s.status = 'idle'

View File

@@ -105,14 +105,16 @@ export const inject = ['command', 'connection', 'locale', 'sessions', 'slots']
* @param ctx - client root context.
*/
export function apply(ctx: ClientContext): void {
ctx.plugin(ModelService)
ctx.effect(() => ctx.locale.register(NS, { zh, en }), 'ui-model: dictionaries')
// Non-slot faces (the command description, the popup option builder) read
// through the bound translate; the seat component reads the standard seat.
const t = ctx.locale.bind(NS)
// The composer-block reason is this plugin's own copy, read at raise time so
// a locale change reaches the next publish.
ctx.plugin(ModelService, { blockReason: () => t('blocked.composer') })
// Entry 1: the /model popupSelect over the shared directory. The command
// description is registry-held text: it reads t() once at registration and
// refreshes only on re-registration, not on locale change.

View File

@@ -25,6 +25,7 @@ export const zh = {
'action.reload': '重新加载',
'warning.groupLoad': '{name} 加载失败:{message}',
'empty.models': '没有可用的模型。',
'blocked.composer': '当前模型不可用,请先选择模型',
'empty.efforts': '当前模型未提供推理等级。',
} satisfies Record<string, string>
@@ -48,5 +49,6 @@ export const en = {
'action.reload': 'Reload',
'warning.groupLoad': '{name} failed to load: {message}',
'empty.models': 'No models available.',
'blocked.composer': 'This model is unavailable — select one to continue',
'empty.efforts': 'This model provides no reasoning effort levels.',
} satisfies Record<ModelKey, string>

View File

@@ -36,11 +36,16 @@ export class ModelService extends Service {
private readonly live: LiveState = { directories: new Map() }
/** Localized composer-block copy; this plugin owns the string it raises. */
private readonly blockReason: () => string
/**
* @param ctx - owning root context (the service registers itself as `models`).
* @param config - the bound translator for this plugin's own dictionary.
*/
constructor(ctx: Context) {
constructor(ctx: Context, config: { blockReason: () => string }) {
super(ctx, 'models')
this.blockReason = config.blockReason
ctx.on('connection/reset', () => {
for (const directory of this.live.directories.values()) directory.resetConnected()
})
@@ -74,6 +79,27 @@ export class ModelService extends Service {
() => sessions.subagentAddress(sessionId) === undefined,
)
live.directories.set(sessionId, directory)
// The composer cannot read this plugin (the dependency runs one way), so
// the block is pushed: the Host says whether an adapter serves the
// session's route, and only a definite `false` makes the input inert.
// `null` — before the first load, or after one failed — must not, or a
// slow or unreachable Host would lock a working composer.
const conversation = this.ctx.get('conversation')
if (conversation !== undefined) {
const publish = (): void => {
conversation.blocks.set(sessionId, directory.store.getSnapshot().routable === false
? { reason: this.blockReason() }
: undefined)
}
publish()
actx.effect(() => {
const stop = directory.store.subscribe(publish)
return () => {
stop()
conversation.blocks.set(sessionId, undefined)
}
}, 'ui-model: composer block')
}
actx.effect(() => () => {
directory.dispose()
live.directories.delete(sessionId)

View File

@@ -17,6 +17,7 @@ import type { ModelTarget } from '@deepseek-ai/dsh-client-connection/client'
import type { CommandContribution, SelectOption } from '@deepseek-ai/dsh-client-ui-command/client'
import type { ModelSelectInjected } from '../src/client/slots.ts'
import { apply, inject } from '../src/client/index.ts'
import { zh } from '../src/client/locales.ts'
const sid = (k: string): SessionId => k as SessionId
@@ -59,7 +60,9 @@ async function bench() {
ctx.provide('connection', { api: { sessions: {
models: () => {
calls.models += 1
return Promise.resolve({ result: { ok: true as const, value: { current, groups: GROUPS, failures: [] } } })
return Promise.resolve({
result: { ok: true as const, value: { current, routable, groups: GROUPS, failures: [] } },
})
},
selectModel: (payload: { provider: string; model: string; reasoningEffort?: string }) => {
calls.select += 1
@@ -73,6 +76,15 @@ async function bench() {
return Promise.resolve({ result: { ok: true as const, value: { selected: current } } })
},
} } })
// Whether the Host reports an adapter for the current route; the composer
// block follows this, never catalog membership.
let routable = true
const blocks = new Map<SessionId, { reason: string } | undefined>()
ctx.provide('conversation', {
blocks: {
set: (id: SessionId, block: { reason: string } | undefined) => { blocks.set(id, block) },
},
})
let contribution: CommandContribution | undefined
ctx.provide('command', {
register(c: CommandContribution) {
@@ -115,6 +127,8 @@ async function bench() {
hostCurrent: () => current,
setHostCurrent: (target: ModelTarget) => { current = target },
address: (id: SessionId) => { addressed.add(id) },
setRoutable: (next: boolean) => { routable = next },
blockOf: (key: string) => blocks.get(sid(key)),
}
}
@@ -217,6 +231,63 @@ describe('ui-model dual entry', () => {
expect(face2.directory).not.toBe(face1.directory)
})
it('blocks the composer only once the Host reports the route unservable', async () => {
const b = await bench()
b.mint('s1')
const face = b.seat().inject!(sid('s1'))
// Before the first load nothing is known. `null` is not `false`: a slow
// or unreachable Host must never lock a working composer.
expect(b.blockOf('s1')).toBeUndefined()
face.load()
await Promise.resolve()
await Promise.resolve()
expect(b.blockOf('s1')).toBeUndefined()
b.setRoutable(false)
b.ctx.emit('models/changed')
await Promise.resolve()
await Promise.resolve()
expect(b.blockOf('s1')?.reason).toBe(zh['blocked.composer'])
// Recovering clears it without a reload of the surface.
b.setRoutable(true)
b.ctx.emit('models/changed')
await Promise.resolve()
await Promise.resolve()
expect(b.blockOf('s1')).toBeUndefined()
})
it('never blocks on catalog membership alone', async () => {
const b = await bench()
b.mint('s1')
const face = b.seat().inject!(sid('s1'))
// A model the route serves but no longer advertises: the seat prompts for
// a selection, the composer stays usable. Blocking here would break a
// supported configuration (a narrowed `models` list over a live route).
b.setHostCurrent({ provider: 'deepseek-official', model: 'unlisted' })
face.load()
await Promise.resolve()
await Promise.resolve()
const snapshot = face.directory.getSnapshot()
expect(snapshot.groups.flatMap(group => group.models.map(model => model.id))).not.toContain('unlisted')
expect(b.blockOf('s1')).toBeUndefined()
})
it('clears its block when the session scope goes', async () => {
const b = await bench()
const scope = b.mint('s1')
b.setRoutable(false)
const face = b.seat().inject!(sid('s1'))
face.load()
await Promise.resolve()
await Promise.resolve()
expect(b.blockOf('s1')).toBeDefined()
await scope.fiber.dispose()
expect(b.blockOf('s1')).toBeUndefined()
})
it('an unknown session fails loud at the seat inject', async () => {
const b = await bench()
expect(() => b.seat().inject!(sid('ghost'))).toThrow(/resolved no scope/)

View File

@@ -32,6 +32,7 @@ const reasoning = {
function state(overrides: Partial<ModelDirectoryState> = {}): ModelDirectoryState {
return {
current: { provider: 'deepseek-official', model: 'deepseek-v4-flash' },
routable: true,
groups: [{
id: 'deepseek-official',
name: 'DeepSeek',