Merge pull request #2404 from deepseek-harness/feat/plugin-owned-settings-surface

feat(settings): serve every registered namespace and key plugin cards on it
This commit is contained in:
Yichen Jiang
2026-08-17 13:51:31 +08:00
committed by GitHub
37 changed files with 851 additions and 214 deletions

View File

@@ -216,7 +216,7 @@ export class AgentPresetSettingsController {
// The roster says what may be chosen; `settings.describe` says whether
// this browser may write the choice down. A non-loopback browser reaches
// neither method, so a refused describe leaves the row read-only rather
// than offering a control whose write answers `settings-not-exposed`.
// than offering a control whose write the Host would refuse.
const described = await this.api.settings.describe({})
this.set({
status: 'ready',

View File

@@ -67,8 +67,8 @@ describe('the agent-preset settings controller', () => {
await controller.load()
// `settings.describe` is loopback-only and reports a read-only provider;
// offering a control whose write answers `settings-not-exposed` would
// promise a switch the host refuses.
// offering a control whose write answers `settings-rejected` would promise
// a switch the host refuses.
expect(controller.store.getSnapshot().writable).toBe(false)
expect(controller.store.getSnapshot().currentValue).toBe('standard')
})

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-settings-plugins/README.md
README.md: 53418f8939649bae4413625a37630e46e7060d15
README.zh.md: 8d4a2bf8d1af662e9f8e05ccc607cc8b66731731
README.md: 92ba426b6bee3ae73e184dfcfd418e889bd47086
README.zh.md: dc319ea9f128016b6df821575cb4d75740f04579

View File

@@ -6,13 +6,13 @@ The **Plugins** settings section and its **Plugin configuration** tab. The secti
## What appears here
A card renders only when its namespace is both registered by a live Host plugin and served to the browser. A deployment that does not compose the owning plugin — or serves the namespace to no client — renders nothing for it rather than an empty or disabled card, so the configurable tab reflects what this deployment actually runs.
The configurable tab reads which settings namespaces the Host serves and dispatches one slot key per namespace, so what renders is the intersection of two ledgers: the namespaces a live Host plugin registered, and the cards registered under those keys. A served namespace no card claims renders nothing — another surface owns it, or this deployment ships no browser half for it — and a card whose namespace this deployment does not serve is never dispatched, so an uncomposed plugin leaves no trace and does not hold the tab back from its empty line. The empty line waits for the Host's first answer, so an unanswered read never reads as "this deployment configures no plugin". Cards appear in the order they registered, which is stable for the cards one package installs together and not stable across plugins: apply order between packages is unconstrained.
The first batch covers the shell executor (`bash`), the agent loop's tool-call parallelism (`agent-loop`), and the DeepSeek search provider (`web-search-deepseek`).
The cards this package ships cover the shell executor (`bash`), the agent loop's tool-call parallelism (`agent-loop`), and the DeepSeek search provider (`web-search-deepseek`).
## Extension point
The section declares `settings.plugins.tab`, a root list slot whose labels become ordered tabs. It keeps a tab mounted after its first selection, so local drafts and read-only snapshots survive tab switches. The package registers its own `configurable` contribution, which declares the nested `settings.plugin.item` list slot. A plugin that ships a browser half registers its own card into that nested slot and owns its controls; this package neither enumerates namespaces nor renders a form it was not given. Both levels follow the contribution's `order`.
The section declares `settings.plugins.tab`, a root list slot whose labels become ordered tabs. It keeps a tab mounted after its first selection, so local drafts and read-only snapshots survive tab switches. The package registers its own `configurable` contribution, which declares the nested `settings.plugin.item` slot — keyed on the settings namespace a card edits. A plugin that ships a browser half registers its own card under its own namespace and owns every part of it: chrome, controls, and copy. Keying on the namespace is what lets a plugin distributed outside this repository appear here — it registers the namespace on the Host and the card in the browser, and the tab pairs the two without learning what the namespace means. Tabs follow the contribution's `order`; cards follow registration order.
## Writes
@@ -35,6 +35,6 @@ None; this package neither assembles nor sends a provider request.
## Known Limitations and Deferred Work
- **Only host-plane plugins appear** — a plugin an agent preset mounts carries its configuration inline in that preset's `agent.cordis.yml` and cannot register a settings namespace at all (a second session mounting the same preset would fail on a duplicate registration), so this section lists nothing for it. Editing those values remains the preset editor's job.
- **Exposure is a Host allowlist, not a plugin declaration** — a namespace absent from the api-proxy's allowlist answers `settings-not-exposed` even when its owner registered it, so a plugin distributed outside this repository cannot surface its own configuration here without a change in `packages/host/apiproxy`.
- **A card still needs a browser bundle** — the browser half must be a `dsh.client` package built in the client module system's lazy-CJS factory format, and the `clientBundle` preset that emits it lives in `packages/client/tsdown.client.ts` rather than a published package, so a plugin outside this repository has to reproduce that build itself. The bundle-purity gate also forbids importing this package's card chrome or form model as values, so such a card owns its own staging and revision fencing.
- **The served namespaces re-read on two signals only** — the wire announces settings-document commits and connection resets, not registrations, so a namespace whose owner registers after the tab's read joins the list on the next document commit or reconnect.
- **The shell card follows the composed executor** — the POSIX and PowerShell executor families share the `bash` namespace because a host composes exactly one of them, so the served schema differs by platform (PowerShell adds `pwshPath`) even though the card edits the same two fields on both, and a deployment composing neither shows no card.
- **The empty line counts registered cards, not visible ones** — a card whose namespace this deployment does not expose renders nothing, but still counts, so a deployment that exposes none shows an empty list rather than the empty line. The count is also read once, because the renderer caches a root entry's inject face; a card registered later does not raise it.

View File

@@ -6,13 +6,13 @@
## 这里会出现什么
只有当某个命名空间既被存活的 Host 插件注册、又被服务给浏览器时,它的卡片才会渲染。未组装该插件的部署——或未向任何客户端服务该命名空间的部署——不会渲染空卡片或禁用卡片,而是什么都不渲染,因此“插件配置”标签页反映的是该部署实际运行的东西。
“插件配置”标签页读取 Host 服务了哪些 settings 命名空间,并为每个命名空间派发一个 slot 键,因此渲染出来的是两份账本的交集:存活 Host 插件注册的命名空间,以及注册在这些键上的卡片。被服务却无人认领的命名空间什么都不渲染——它归别的界面所有,或本部署没有为它提供浏览器半侧;而命名空间未被本部署服务的卡片根本不会被派发,因此未组装的插件不留任何痕迹,也不会挡住那行空态文案。空态文案要等 Host 的第一次答复,因此一次尚未答复的读取绝不会被读成“本部署没有可配置的插件”。卡片按自身注册的顺序出现;对同一个包一起安装的卡片这是稳定的,对跨插件的卡片则不稳定:包与包之间的 apply 顺序是无约束的。
第一批覆盖 shell 执行器(`bash`)、agent 循环的工具调用并行度(`agent-loop`)以及 DeepSeek 搜索提供方(`web-search-deepseek`)。
本包自带的卡片覆盖 shell 执行器(`bash`)、agent 循环的工具调用并行度(`agent-loop`)以及 DeepSeek 搜索提供方(`web-search-deepseek`)。
## 扩展点
本分区声明根级列表 slot `settings.plugins.tab`,其标签会成为有序标签页。某个标签页首次被选择后会保持挂载,因此本地草稿与只读快照在切换标签页时不会丢失。本包注册自己的 `configurable` 贡献,由它声明嵌套的 `settings.plugin.item` 列表 slot。带浏览器半侧的插件把自己的卡片注册进这个嵌套 slot 并拥有其控件;本包既不枚举命名空间,也不渲染未被交给它的表单。两层排序都遵循贡献的 `order`。
本分区声明根级列表 slot `settings.plugins.tab`,其标签会成为有序标签页。某个标签页首次被选择后会保持挂载,因此本地草稿与只读快照在切换标签页时不会丢失。本包注册自己的 `configurable` 贡献,由它声明嵌套的 `settings.plugin.item` slot——以卡片所编辑的 settings 命名空间为键。带浏览器半侧的插件把自己的卡片注册在自己的命名空间上,并拥有它的全部:外观、控件与文案。以命名空间为键,正是在本仓库之外分发的插件能出现在这里的原因——它在 Host 上注册命名空间、在浏览器里注册卡片,由标签页把两者配对,而无需知道命名空间意味着什么。标签页遵循贡献的 `order`;卡片遵循注册顺序。
## 写入
@@ -35,6 +35,6 @@
## 已知限制与暂缓事项
- **只有宿主平面的插件会出现**——由 agent preset 挂载的插件把配置内联在该 preset 的 `agent.cordis.yml` 中,且根本无法注册 settings 命名空间(同一 preset 挂载第二个会话时会因重复注册而失败),因此本分区不会列出它。编辑那些值仍是 preset 编辑器的职责。
- **暴露是 Host 的白名单,而非插件的声明**——不在 api-proxy 白名单中的命名空间,即便其拥有方已注册,也只会得到 `settings-not-exposed`,因此在本仓库之外分发的插件无法在不改动 `packages/host/apiproxy` 的前提下让自己的配置出现在这里。
- **卡片仍然需要一份浏览器 bundle**——浏览器半侧必须是按客户端模块系统的 lazy-CJS factory 格式构建的 `dsh.client` 包,而产出它的 `clientBundle` 预设位于 `packages/client/tsdown.client.ts`,并非已发布的包,因此本仓库之外的插件得自行复刻该构建。bundle 纯净度门禁同时禁止以值的形式导入本包的卡片外观与表单模型,所以这样的卡片要自行拥有暂存与 revision 设栅。
- **被服务的命名空间只在两种信号上重读**——协议通告的是 settings 文档提交与连接重置,而非注册行为,因此在标签页读取之后才被其拥有方注册的命名空间,要等下一次文档提交或重连才会加入列表。
- **shell 卡片跟随被组装的执行器**——POSIX 与 PowerShell 两个执行器家族共用 `bash` 命名空间,因为一个宿主只组装其中之一,所以被服务的 schema 随平台不同(PowerShell 多出 `pwshPath`),尽管卡片在两者下编辑的都是同样两个字段;而两者都不组装的部署不会显示这张卡片。
- **空态数的是已注册卡片,不是可见卡片**——命名空间未被本部署暴露的卡片什么都不渲染,但仍计入数量,因此一个都不暴露的部署看到的是空列表而非那行空态文案。该计数还只读取一次,因为渲染器会缓存根级 entry 的 inject face;之后注册的卡片不会让它变大。

View File

@@ -1,25 +1,43 @@
/** Configurable Host plugins contributed to the shared Plugins section. */
/**
* Configurable Host plugins contributed to the shared Plugins section.
*
* The tab enumerates settings namespaces but never interprets one — a card
* arrives through `settings.plugin.item` keyed by the namespace it edits, so a
* plugin that ships a browser half owns its own card and this tab only decides
* which keys to dispatch.
*/
import { Fragment } from 'react'
import type { InjectFace, PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import type {} from './slot-contract.ts'
import type { ConfigurablePluginsTabFace } from './tab-store.ts'
import css from './PluginsSettingsSection.module.css'
/** Registration-side business face for the configurable tab. */
export interface ConfigurablePluginsTabInjected {
/** How many cards the slot ledger held when the tab registration mounted. */
cardCount: number
}
/** Props the renderer binds for the configurable tab. */
export type ConfigurablePluginsTabProps =
PropsRuntime<'settings.plugins.tab'>
& PropsLocale<'settings.plugins'>
& PropsRenderSlots<'settings.plugin.item'>
& InjectFace<ConfigurablePluginsTabInjected>
& InjectFace<ConfigurablePluginsTabFace>
/** Render cards registered by plugins that expose editable settings. */
export function ConfigurablePluginsTab({ t, renderSlot, cardCount }: ConfigurablePluginsTabProps) {
return cardCount === 0
? <p className={css.empty}>{t('empty')}</p>
: <ul className={css.cards}>{renderSlot('settings.plugin.item', {})}</ul>
/**
* Render cards registered by plugins that expose editable settings.
* @param props - locale copy, slot rendering, and the namespaces to dispatch.
* @returns the card list, or the empty line once the Host has answered.
*/
export function ConfigurablePluginsTab(props: ConfigurablePluginsTabProps) {
const { t, renderSlot } = props
const { loaded, namespaces } = props.useConfigurablePlugins(snapshot => snapshot)
if (namespaces.length > 0) {
return (
<ul className={css.cards}>
{namespaces.map(ns => (
// One dispatch per namespace, so the list identity is the namespace
// rather than a position that shifts as cards arrive.
<Fragment key={ns}>{renderSlot('settings.plugin.item', {}, { entryKey: ns })}</Fragment>
))}
</ul>
)
}
return loaded ? <p className={css.empty}>{t('empty')}</p> : null
}

View File

@@ -23,17 +23,18 @@ import type {} from '@deepseek-ai/dsh-api-remotes/client'
import { AgentLoopCard } from './AgentLoopCard.tsx'
import { BashCard } from './BashCard.tsx'
import { ConfigurablePluginsTab } from './ConfigurablePluginsTab.tsx'
import type { ConfigurablePluginsTabInjected } from './ConfigurablePluginsTab.tsx'
import { PluginsSettingsSection } from './PluginsSettingsSection.tsx'
import type { PluginsSettingsSectionInjected, PluginsSettingsTabEntry } from './PluginsSettingsSection.tsx'
import { WebSearchCard } from './WebSearchCard.tsx'
import { AGENT_LOOP_NS, AgentLoopCardController } from './agent-loop-card-controller.ts'
import { SHELL_NS, BashCardController } from './bash-card-controller.ts'
import { ConfigurablePluginsTabController } from './tab-store.ts'
import { WEB_SEARCH_NS, WebSearchCardController } from './web-search-card-controller.ts'
import { en, zh } from './locales.ts'
export type { PluginsSettingsSectionInjected, PluginsSettingsSectionProps } from './PluginsSettingsSection.tsx'
export type { ConfigurablePluginsTabInjected, ConfigurablePluginsTabProps } from './ConfigurablePluginsTab.tsx'
export type { ConfigurablePluginsTabProps } from './ConfigurablePluginsTab.tsx'
export type { ConfigurablePluginsTabFace, ConfigurablePluginsTabState } from './tab-store.ts'
export type { PluginCardProps } from './PluginCard.tsx'
export type { SettingsPluginItemOwnerProps } from './slot-contract.ts'
export type { FieldProps } from './fields.tsx'
@@ -71,6 +72,27 @@ export function apply(ctx: ClientContext): void {
'ui-settings-plugins: credential invalidations',
)
// Which namespaces the Host serves is a registration fact the wire does not
// announce, so the directory re-reads on the two signals that can carry a
// changed composition: a settings document commit and a reconnect.
const configurable = new ConfigurablePluginsTabController(
api, () => ctx.slots.entries('settings.plugin.item'))
ctx.effect(() => () => { configurable.dispose() }, 'ui-settings-plugins: tab directory')
ctx.effect(
() => ctx.remote.$on('settings/document-updated', () => { void configurable.load() }),
'ui-settings-plugins: served-namespace invalidations',
)
ctx.effect(
() => ctx.on('connection/reset', () => { void configurable.load() }),
'ui-settings-plugins: served-namespace reconnect',
)
// A card registered after the first read joins the list without a wire call.
ctx.effect(
() => ctx.slots.subscribe('settings.plugin.item', () => { configurable.refresh() }),
'ui-settings-plugins: card ledger',
)
void configurable.load()
let tabsVersion = -1
let tabsRevision = -1
let tabs: readonly PluginsSettingsTabEntry[] = []
@@ -126,31 +148,26 @@ export function apply(ctx: ClientContext): void {
order: 0,
label: () => t('configurableTab'),
locale: NS,
inject: (): ConfigurablePluginsTabInjected => ({
cardCount: ctx.slots.entries('settings.plugin.item').length,
}),
children: { 'settings.plugin.item': { kind: 'list', scope: 'root' } },
inject: () => configurable.inject(),
children: { 'settings.plugin.item': { kind: 'keyed', scope: 'root' } },
}, ConfigurablePluginsTab))
ctx.slots.inject('settings.plugin.item', function* () {
yield ctx.slots.register({
name: 'settings.plugin.item',
id: 'bash',
order: 0,
key: SHELL_NS,
locale: NS,
inject: () => bash.inject(),
}, BashCard)
yield ctx.slots.register({
name: 'settings.plugin.item',
id: 'agent-loop',
order: 10,
key: AGENT_LOOP_NS,
locale: NS,
inject: () => agentLoop.inject(),
}, AgentLoopCard)
yield ctx.slots.register({
name: 'settings.plugin.item',
id: 'web-search',
order: 20,
key: WEB_SEARCH_NS,
locale: NS,
inject: () => webSearch.inject(),
}, WebSearchCard)

View File

@@ -1,19 +1,22 @@
/**
* The `settings.plugin.item` slot type — one plugin's card inside the plugin
* configuration section. Options: `id` (card key), `order` (card position).
* A card draws its own internals; the section only stacks them and reports
* how many there are.
* The `settings.plugin.item` slot type — one plugin's card inside the
* configurable-plugins tab, keyed by the settings namespace the card edits.
* Options: `key` (the namespace). A card draws its own internals; the tab only
* decides which namespaces to dispatch and stacks what comes back.
*
* TYPE HOME RATIONALE: unlike `settings.general.item`, whose registrants span
* packages that cannot reference its declarer, every current registrant of
* this slot ships in this package, and a plugin registering its own card
* already depends on this package for the card chrome. The type therefore
* lives with the section that declares it at runtime.
* Keying on the namespace is what lets a plugin distributed outside this
* repository contribute a card: it registers its own settings namespace on the
* Host and its own card under that key in the browser, and the tab pairs the
* two without ever learning what the namespace means.
*
* TYPE HOME RATIONALE: the tab declares this slot at runtime, and a plugin
* registering its own card already depends on this package for the slot's
* declaration. The type therefore lives with its declarer.
*/
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface SlotMap {
/** One plugin's card inside the plugin configuration section (see module JSDoc). */
'settings.plugin.item': { kind: 'list'; scope: 'root'; owner: SettingsPluginItemOwnerProps }
'settings.plugin.item': { kind: 'keyed'; scope: 'root'; owner: SettingsPluginItemOwnerProps }
}
}

View File

@@ -0,0 +1,123 @@
/**
* The configurable-plugins tab's card list.
*
* The tab dispatches its slot by settings namespace, so what it renders is
* the intersection of two ledgers: the namespaces the Host serves and the
* cards registered into `settings.plugin.item`. A served namespace no card
* claims renders nothing — another surface owns it, or this deployment ships
* no browser half for it — and a card whose namespace the Host does not serve
* is never dispatched, so a plugin this deployment did not compose leaves no
* trace and does not count toward the empty line.
*/
import type { IApiClient } from '@deepseek-ai/dsh-client-connection/client'
import type { StoredEntry } from '@deepseek-ai/dsh-client-ui-slots'
import { createSnapshotStore, type SnapshotStore } from '@deepseek-ai/dsh-client-runtime/client'
/** What the section renders. */
export interface ConfigurablePluginsTabState {
/**
* Whether the Host has answered once. The empty line waits for it: an
* unanswered read is not the same statement as "this deployment configures
* no plugin", and saying the second while the first is true would flash a
* wrong answer on every open.
*/
loaded: boolean
/**
* Namespaces to dispatch, in the order their cards registered, narrowed to
* those the Host serves. Card registration order rather than the Host's
* description order: the latter follows plugin activation, which async
* settings injection can reorder between boots, and a settings page whose
* cards move between visits is worse than one whose order a registrant
* chose.
*/
namespaces: string[]
}
/** The registration-side face the tab's slot entry injects. */
export interface ConfigurablePluginsTabFace {
hooks: {
/** Section snapshot bound by the renderer as usePluginConfigSection. */
configurablePlugins: SnapshotStore<ConfigurablePluginsTabState>
}
}
/** Reads the served namespaces and pairs them with the cards that claim them. */
export class ConfigurablePluginsTabController {
private readonly store = createSnapshotStore<ConfigurablePluginsTabState>({ loaded: false, namespaces: [] })
/** Last Host answer; kept so a slot mutation republishes without a wire read. */
private served: readonly string[] = []
private loaded = false
private generation = 0
private disposed = false
/**
* @param api - settings wire face.
* @param entries - reads the cards currently registered into the section's slot.
*/
constructor(
private readonly api: Pick<IApiClient, 'settings'>,
private readonly entries: () => readonly StoredEntry[],
) {}
/** Opaque read of {@link disposed}: control flow cannot narrow it across awaits. */
private isDisposed(): boolean {
return this.disposed
}
/**
* Re-read the served namespaces from the Host and republish.
* @returns settlement after the read, or immediately once disposed.
*/
async load(): Promise<void> {
if (this.isDisposed()) return
const generation = ++this.generation
let response: Awaited<ReturnType<IApiClient['settings']['describe']>>
try {
response = await this.api.settings.describe({})
} catch (_settingsReadFailure) {
// The tab keeps the namespaces it last knew; the next invalidation
// or reconnect reads again.
return
}
if (this.isDisposed() || generation !== this.generation || !response.result.ok) return
this.served = response.result.value.namespaces.map(view => view.ns)
this.loaded = true
this.publish()
}
/** Republish after the slot ledger changed; a card registered late joins here. */
refresh(): void {
if (this.disposed) return
this.publish()
}
/** Stop publishing; an in-flight read settles without touching the store. */
dispose(): void {
this.disposed = true
this.generation += 1
}
/**
* Build the face the tab's slot registration injects.
* @returns the tab's snapshot source.
*/
inject(): ConfigurablePluginsTabFace {
return { hooks: { configurablePlugins: this.store } }
}
private publish(): void {
const served = new Set(this.served)
const namespaces = this.entries().flatMap(entry =>
entry.options.key !== undefined && served.has(entry.options.key) ? [entry.options.key] : [])
const previous = this.store.getSnapshot()
// Every settings-document commit re-reads, and most of them change nothing
// this section shows. An observable source must keep its snapshot
// reference until the fact moves, or each unrelated save re-renders the
// whole card list (packages/client/AGENTS.md reactive rule 5).
if (previous.loaded === this.loaded
&& previous.namespaces.length === namespaces.length
&& previous.namespaces.every((ns, index) => ns === namespaces[index])) return
this.store.set({ loaded: this.loaded, namespaces })
}
}

View File

@@ -16,8 +16,8 @@ export const inject = ['invariants']
/**
* No runtime invariant: this is a browser-side settings surface whose node half owns no event
* stream or mutable runtime data; the layering, write refusals, and exposure boundary are Host
* contracts covered by the owning plugins and the api-proxy.
* stream or mutable runtime data; the layering and write refusals are Host contracts covered by
* the owning plugins and the api-proxy.
*/
const install: InvariantInstaller = () => {}

View File

@@ -9,19 +9,38 @@ import { TestRemote, usePinnedBrowserLanguages } from '@deepseek-ai/dsh-client-t
import { SettingsScopeBinder } from '@deepseek-ai/dsh-client-ui-settings/client'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-plugins/client'
import type {
ConfigurablePluginsTabInjected, PluginsSettingsSectionInjected,
ConfigurablePluginsTabFace, PluginsSettingsSectionInjected,
} from '@deepseek-ai/dsh-client-ui-settings-plugins/client'
// The service reads its initial locale from the browser; these specs assert
// the shipped Chinese copy, so they state the browser they assume.
usePinnedBrowserLanguages('zh-CN')
async function bench() {
/**
* @param served - namespaces the Host describes; omitted answers a failed read,
* which is what most of these specs want (no card has anything to render).
*/
async function bench(served?: string[]) {
const ctx = new Context()
await ctx.plugin(SlotRegistry).await()
const locale = new LocaleRuntime(ctx)
ctx.provide('locale', locale)
const describeCredentials = vi.fn(() => Promise.resolve({ rpcId: 'c', result: { ok: false, error: {} } }))
const describeSettings = vi.fn(() => Promise.resolve(served === undefined
? { rpcId: 's', result: { ok: false, error: {} } }
: {
rpcId: 's',
result: {
ok: true,
value: {
writable: true,
hasDocument: true,
namespaces: served.map(ns => ({
ns, schema: {}, value: {}, applies: 'live', secrets: [], revision: 0,
})),
},
},
}))
// The section binds its scopes through the Settings surface's service, and
// forwarded Host events reach it through the same `$dispatch` handoff the
// connection sink makes.
@@ -29,12 +48,12 @@ async function bench() {
ctx.provide('connection', {
isLoopback: true,
api: {
settings: { describe: vi.fn(() => Promise.resolve({ rpcId: 's', result: { ok: false, error: {} } })) },
settings: { describe: describeSettings },
credentials: { describe: describeCredentials },
},
} as never)
await ctx.plugin(SettingsScopeBinder).await()
return { ctx, slots: ctx.get('slots') as SlotRegistry, describeCredentials }
return { ctx, slots: ctx.get('slots') as SlotRegistry, describeCredentials, describeSettings }
}
function declareRoot(slots: SlotRegistry): () => void {
@@ -63,20 +82,11 @@ describe('ui-settings-plugins apply', () => {
const tab = slots.entries('settings.plugins.tab')[0]!
expect(tab.options).toMatchObject({ id: 'configurable', order: 0 })
expect(resolveSlotLabel(tab.options.label)).toBe('插件配置')
expect(slots.spec('settings.plugin.item')).toMatchObject({ kind: 'list', scope: 'root' })
expect(slots.spec('settings.plugin.item')).toMatchObject({ kind: 'keyed', scope: 'root' })
})
it('registers one card per host-plane section it ships, in a stable order', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
expect(slots.entries('settings.plugin.item').map(entry => entry.options.id))
.toEqual(['bash', 'agent-loop', 'web-search'])
})
it('injects a live tab projection, a card count, and one business face per card', async () => {
it('injects a live tab projection, the card directory, and one business face per card', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
@@ -99,7 +109,8 @@ describe('ui-settings-plugins apply', () => {
unsubscribe()
const tab = slots.entries('settings.plugins.tab')[0]!
expect((tab.inject as unknown as () => ConfigurablePluginsTabInjected)()).toEqual({ cardCount: 3 })
const tabFace = (tab.inject as unknown as () => ConfigurablePluginsTabFace)()
expect(Object.keys(tabFace.hooks)).toEqual(['configurablePlugins'])
for (const entry of slots.entries('settings.plugin.item')) {
const face = (entry as { inject?: () => unknown }).inject?.() as { hooks: Record<string, unknown> }
// Each card injects exactly one snapshot store plus its own actions.
@@ -107,6 +118,58 @@ describe('ui-settings-plugins apply', () => {
}
})
it('keys each card it ships on the settings namespace that card edits', async () => {
const { ctx, slots } = await bench()
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
expect(slots.entries('settings.plugin.item').map(entry => entry.options.key))
.toEqual(['shell', 'agent-loop', 'web-search-deepseek'])
})
it('dispatches the served namespaces its cards claim, and no others', async () => {
// ui-theme is served but belongs to another surface, and a deployment
// composing no PowerShell/POSIX executor serves no `bash` at all.
const { ctx, slots } = await bench(['agent-loop', 'ui-theme', 'web-search-deepseek'])
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
const tab = slots.entries('settings.plugins.tab')[0]!
const face = (tab.inject as unknown as () => ConfigurablePluginsTabFace)()
await vi.waitFor(() => {
expect(face.hooks.configurablePlugins.getSnapshot().namespaces)
.toEqual(['agent-loop', 'web-search-deepseek'])
})
})
it('re-reads the served namespaces when the Host commits a settings document', async () => {
// Which namespaces the Host serves is a registration fact the wire never
// announces on its own, so the tab rides the invalidation that can
// accompany a changed composition.
const { ctx, slots, describeSettings } = await bench(['bash'])
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
await vi.waitFor(() => { expect(describeSettings).toHaveBeenCalled() })
describeSettings.mockClear()
ctx.remote.$dispatch('settings/document-updated', ['bash', 1])
await vi.waitFor(() => { expect(describeSettings).toHaveBeenCalled() })
})
it('re-reads the served namespaces after a reconnect', async () => {
const { ctx, slots, describeSettings } = await bench(['bash'])
declareRoot(slots)
await ctx.plugin({ inject: [...inject], apply }).await()
await vi.waitFor(() => { expect(describeSettings).toHaveBeenCalled() })
describeSettings.mockClear()
ctx.emit('connection/reset')
await vi.waitFor(() => { expect(describeSettings).toHaveBeenCalled() })
})
it('re-reads the credential when the Host reports the watched reference changed', async () => {
const { ctx, slots, describeCredentials } = await bench()
declareRoot(slots)

View File

@@ -22,6 +22,7 @@ import type { WebSearchCardProps } from '../src/client/WebSearchCard.tsx'
import type { AgentLoopCardState } from '../src/client/agent-loop-card-controller.ts'
import type { BashCardState } from '../src/client/bash-card-controller.ts'
import type { CardFieldState, CardShell } from '../src/client/card-form.ts'
import type { ConfigurablePluginsTabState } from '../src/client/tab-store.ts'
import type { WebSearchCardState } from '../src/client/web-search-card-controller.ts'
import { en } from '../src/client/locales.ts'
@@ -59,11 +60,20 @@ function renderSection(rows: readonly PluginsSettingsTabEntry[]) {
render(<PluginsSettingsSection {...props} />)
}
function renderConfigurable(cardCount: number, cards = 'cards') {
/**
* Render the tab over the namespaces it was told to dispatch, with `cards`
* standing in for the slot ledger: a key it names renders that text, and one
* it does not renders nothing, exactly as an unclaimed key does.
*/
function renderConfigurable(namespaces: string[], cards: Record<string, string> = {}, loaded = true) {
const store = createSnapshotStore<ConfigurablePluginsTabState>({ loaded, namespaces })
const props = {
t,
cardCount,
renderSlot: () => <li>{cards}</li>,
useConfigurablePlugins: bindSnapshotSelector(store),
renderSlot: (_name: string, _owner: object, opts?: { entryKey?: string }) => {
const card = opts?.entryKey === undefined ? undefined : cards[opts.entryKey]
return card === undefined ? null : <li>{card}</li>
},
} as unknown as ConfigurablePluginsTabProps
render(<ConfigurablePluginsTab {...props} />)
}
@@ -153,16 +163,24 @@ describe('PluginsSettingsSection', () => {
describe('ConfigurablePluginsTab', () => {
it('says so when no plugin contributed a card', () => {
renderConfigurable(0)
renderConfigurable([], { bash: 'shell' })
expect(screen.getByText(en.empty)).toBeTruthy()
expect(screen.queryByText('cards')).toBeNull()
expect(screen.queryByText('shell')).toBeNull()
})
it('renders the card list once a plugin contributed one', () => {
renderConfigurable(1)
it('withholds the empty line until the Host has answered once', () => {
// An unanswered read is not the statement that this deployment configures
// no plugin; saying it anyway would flash a wrong answer on every open.
renderConfigurable([], { bash: 'shell' }, false)
expect(screen.getByText('cards')).toBeTruthy()
expect(screen.queryByText(en.empty)).toBeNull()
})
it('dispatches one card per namespace, keyed by it', () => {
renderConfigurable(['bash', 'agent-loop'], { bash: 'shell', 'agent-loop': 'loop' })
expect(screen.getAllByRole('listitem').map(item => item.textContent)).toEqual(['shell', 'loop'])
expect(screen.queryByText(en.empty)).toBeNull()
})
})

View File

@@ -8,6 +8,7 @@ import { stubSettingsScope, type StubSettingsScope } from '@deepseek-ai/dsh-clie
import { CardForm, numberField, textField } from '../src/client/card-form.ts'
import { AgentLoopCardController, type AgentLoopSettings } from '../src/client/agent-loop-card-controller.ts'
import { BashCardController, type BashSettings } from '../src/client/bash-card-controller.ts'
import { ConfigurablePluginsTabController } from '../src/client/tab-store.ts'
import { WebSearchCardController, type WebSearchSettings } from '../src/client/web-search-card-controller.ts'
/** Make the stub behave like a Host that accepts every write. */
@@ -380,7 +381,7 @@ describe('AgentLoopCardController', () => {
})
describe('WebSearchCardController', () => {
it('reads the credential state for the reference the section names', async () => {
it('reads the credential state for the reference the tab names', async () => {
const host = stubSettingsScope<WebSearchSettings>()
const credentials = credentialsApi(true)
const controller = new WebSearchCardController(host.scope, credentials.api)
@@ -460,7 +461,7 @@ describe('WebSearchCardController', () => {
})
})
it('addresses the reference the section declares rather than the default', async () => {
it('addresses the reference the tab declares rather than the default', async () => {
const host = stubSettingsScope<WebSearchSettings>()
const credentials = credentialsApi(false)
const controller = new WebSearchCardController(host.scope, credentials.api)
@@ -538,3 +539,131 @@ describe('WebSearchCardController', () => {
expect(credentials.set).not.toHaveBeenCalled()
})
})
describe('ConfigurablePluginsTabController', () => {
function settingsApi(namespaces: string[]) {
const describe = vi.fn(() => Promise.resolve({
rpcId: 's-1' as never,
result: {
ok: true as const,
value: {
writable: true,
hasDocument: true,
namespaces: namespaces.map(ns => ({
ns, schema: {}, value: {}, applies: 'live' as const, secrets: [], revision: 0,
})),
},
},
}))
return { api: { settings: { describe } } as never, describe }
}
/** Slot ledger stand-in: one stored entry per registered card key. */
function ledger(...keys: string[]) {
return keys.map(key => ({ component: null, options: { key } }))
}
it('dispatches the served namespaces a card claims, in card registration order', async () => {
const settings = settingsApi(['bash', 'ui-theme', 'agent-loop'])
const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('agent-loop', 'bash'))
await controller.load()
// ui-theme is served but claimed by no card here — another surface owns
// it. The order is the cards', not the Host's: plugin activation can
// reorder the description between boots.
expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces)
.toEqual(['agent-loop', 'bash'])
})
it('never dispatches a card whose namespace this deployment does not serve', async () => {
const settings = settingsApi(['bash'])
const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash', 'web-search-deepseek'))
await controller.load()
expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash'])
})
it('takes a card registered after the read without asking the Host again', async () => {
const settings = settingsApi(['bash'])
let entries = ledger()
const controller = new ConfigurablePluginsTabController(settings.api, () => entries)
await controller.load()
expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual([])
entries = ledger('bash')
controller.refresh()
expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash'])
expect(settings.describe).toHaveBeenCalledOnce()
})
it('keeps the namespaces it knew when a read fails', async () => {
const settings = settingsApi(['bash'])
const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash'))
await controller.load()
settings.describe.mockRejectedValueOnce(new Error('offline'))
await controller.load()
expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash'])
})
it('publishes nothing once disposed, and never claims it was answered', async () => {
const settings = settingsApi(['bash'])
const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash'))
controller.dispose()
await controller.load()
expect(controller.inject().hooks.configurablePlugins.getSnapshot())
.toEqual({ loaded: false, namespaces: [] })
expect(settings.describe).not.toHaveBeenCalled()
})
it('ignores a slot-ledger change that arrives after disposal', async () => {
const settings = settingsApi(['bash'])
let entries = ledger()
const controller = new ConfigurablePluginsTabController(settings.api, () => entries)
await controller.load()
controller.dispose()
entries = ledger('bash')
controller.refresh()
expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual([])
})
it('drops a read a newer one superseded', async () => {
// The section re-reads on every settings-document invalidation, so a slow
// first answer must not overwrite the newer one that already landed.
const settings = settingsApi(['bash'])
const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash', 'agent-loop'))
const slow = Promise.withResolvers<unknown>()
settings.describe.mockReturnValueOnce(slow.promise as never)
const stale = controller.load()
await controller.load()
expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash'])
slow.resolve({
rpcId: 's-0',
result: { ok: true, value: { writable: true, hasDocument: true, namespaces: [
{ ns: 'agent-loop', schema: {}, value: {}, applies: 'live', secrets: [], revision: 0 },
] } },
})
await stale
expect(controller.inject().hooks.configurablePlugins.getSnapshot().namespaces).toEqual(['bash'])
})
it('reports the Host answered even when it serves nothing this tab shows', async () => {
const settings = settingsApi(['ui-theme'])
const controller = new ConfigurablePluginsTabController(settings.api, () => ledger('bash'))
await controller.load()
expect(controller.inject().hooks.configurablePlugins.getSnapshot())
.toEqual({ loaded: true, namespaces: [] })
})
})