feat(permission): add new-session default setting

This commit is contained in:
Yichen Jiang
2026-07-31 12:48:19 +08:00
parent 4a061f33d0
commit ee74b5b07a
51 changed files with 1452 additions and 226 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-permission/README.md
README.md: 3377a1c5907b67b065879b012923427685c106d6
README.zh.md: 34cf6f72394632968ded1671a5ac0377e5c78cc6
README.md: adb56edfc461d982b436159f025dbd65ae14dd83
README.zh.md: c5b7c9efeb0c8688be3704c66baaeeef24831301

View File

@@ -2,13 +2,15 @@
English | [中文](README.zh.md)
Permission preset selection plugin, browser half: a popupSelect DECORATION hung on the host `/permission` command (`ctx.command.decorate`). A decoration is not a second command — the host command keeps its slash-menu row, the argued path (`/permission <preset>` switches directly), and the durable lifecycle logging; the decoration replaces only the bare invocation with the picker: one flat preset list with the current value marked active and kebab-case preset names rendered as title-case labels (`workspace-write` → `Workspace Write`, the composer chip's display transform twin), where a pick submits the `/permission <preset>` command line. Options and the active mark read the session's `permissions` projection (the same host-computed select the composer chip renders), so both surfaces share one read source and one write path, and the pushed projection frame is the single confirmation both follow. The decoration is available exactly while the projection key is present; a permission-less composition shows no picker (a decoration never manufactures a catalog row).
Permission browser surfaces for two different lifetimes. The General-settings row reads the explicitly exposed `permission` Settings descriptor, derives its options from the host's dynamic `defaultPreset` enum, and writes one `settings.mutate` path operation with the descriptor revision. A push invalidation refetches the descriptor. This value applies only when a later session is created; changing it does not switch the current session.
The current-session surface remains a popupSelect DECORATION hung on the host `/permission` command (`ctx.command.decorate`). A decoration is not a second command — the host command keeps its slash-menu row, the argued path (`/permission <preset>` switches directly), and the durable lifecycle logging; the decoration replaces only the bare invocation with the picker: one flat preset list with the current value marked active and kebab-case preset names rendered as title-case labels (`workspace-write` → `Workspace Write`, the composer chip's display transform twin), where a pick submits the `/permission <preset>` command line. Options and the active mark read the session's `permissions` projection (the same host-computed select the composer chip renders), so both current-session surfaces share one read source and one write path, and the pushed projection frame is the single confirmation both follow. The decoration is available exactly while the projection key is present; a permission-less composition shows neither picker nor Settings row.
The `/client` export surface is the plugin body (`apply`/`inject`).
## Model Experience
Indirectly, through the host `/permission` command the picker submits: a switch appends the whole-value knob events (`permission/preset`, `sandbox/mode`, `approval/policy`), which select the sandbox mode and approval policy later tool calls resolve. Picker interaction adds no prompt content.
Indirectly, through the permission facts written by its two surfaces: the Settings row causes a future session to start with whole-value knob events (`permission/preset`, `sandbox/mode`, `approval/policy`), while the `/permission` picker appends the same facts when it switches the current session; those events select the sandbox mode and approval policy later tool calls resolve, and picker interaction adds no prompt content.
#### KV Cache effect
@@ -16,4 +18,4 @@ No direct invalidation; the knob consumers own any request-prefix changes.
## Known Limitations and Deferred Work
- **No keyless snapshot exercises the picker yet** — the popup flow is covered by unit specs over fake faces; the assembled-transcript scenario rides the deferred approval/preset e2e work.
- **The Settings row is Web-only** — non-Web clients may still switch the current session through `/permission`, but do not receive this browser contribution.

View File

@@ -2,13 +2,15 @@
[English](README.md) | 中文
权限预设选择插件(浏览器半侧):挂在 host `/permission` 命令上的 popupSelect **装饰**(`ctx.command.decorate`)。装饰不是第二条命令——host 命令保留斜杠菜单行、带参路径(`/permission <preset>` 直接切换)与持久生命周期记账;装饰只把裸调用替换为选择框:一张扁平预设列表,当前值标记为 active,kebab-case 预设名渲染为 Title Case 标签(`workspace-write` → `Workspace Write`,与 composer chip 的显示变换孪生),选中即提交 `/permission <preset>` 命令行。选项与 active 标记读取会话的 `permissions` 投影(与 composer chip 渲染的同一份 host 计算 select),因此两个界面共享同一读源与同一写路径,推送的投影帧是两者共同跟随的唯一确认。装饰恰在投影 key 存在时可用;无权限组合不显示选择框(装饰绝不无中生有目录行)。
面向两种不同生命周期的浏览器权限界面。「通用」设置行读取显式暴露的 `permission` Settings 描述符,从 host 的动态 `defaultPreset` enum 中推导选项,并携带描述符的 revision 写入一条 `settings.mutate` 路径操作。推送的失效通知会重新获取描述符。这个值仅在后续会话创建时生效;改变它不会切换当前会话。
当前会话界面仍是挂在 host `/permission` 命令上的 popupSelect **装饰**(`ctx.command.decorate`)。装饰不是第二条命令——host 命令保留斜杠菜单行、带参路径(`/permission <preset>` 直接切换)与持久生命周期记账;装饰只把裸调用替换为选择框:一张扁平预设列表,当前值标记为 active,kebab-case 预设名渲染为 Title Case 标签(`workspace-write` → `Workspace Write`,与 composer chip 的显示变换孪生),选中即提交 `/permission <preset>` 命令行。选项与 active 标记读取会话的 `permissions` 投影(与 composer chip 渲染的同一份 host 计算 select),因此两个当前会话界面共享同一读源与同一写路径,推送的投影帧是两者共同跟随的唯一确认。装饰恰在投影 key 存在时可用;无权限组合既不显示选择框,也不显示 Settings 行。
`/client` 导出面为插件本体(`apply`/`inject`)。
## Model Experience
间接影响,经由选择框提交的 host `/permission` 命令:一次切换追加全量值旋钮事件(`permission/preset`、`sandbox/mode`、`approval/policy`),决定后续工具调用解析到的沙箱模式与审批策略。选择框交互本身不添加任何提示词内容。
通过两个界面写入的权限事实间接影响:Settings 行使未来会话带着全量值旋钮事件(`permission/preset`、`sandbox/mode`、`approval/policy`)启动,而 `/permission` 选择框切换当前会话时会追加相同的事实;这些事件决定后续工具调用解析到的沙箱模式与审批策略,选择框交互本身不添加任何提示词内容。
#### KV Cache effect
@@ -16,4 +18,4 @@
## Known Limitations and Deferred Work
- **尚无无密钥快照覆盖选择框** —— popup 流程由基于 fake face 的单元 spec 覆盖;组装态转写场景随延后的审批/预设 e2e 工作一并补齐。
- **Settings 行仅在 Web 中可用**:非 Web 客户端仍可通过 `/permission` 切换当前会话,但不会获得这项浏览器贡献。

View File

@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-client-ui-permission",
"description": "Permission preset selection: the /permission popupSelect over the permissions projection and the host /permission command",
"description": "Permission surfaces: a new-session default in General settings and a current-session /permission popup over the permissions projection",
"version": "0.0.1",
"private": true,
"type": "module",
@@ -24,8 +24,10 @@
},
"dshClient": {
"inject": [
"@deepseek-ai/dsh-client-connection",
"@deepseek-ai/dsh-client-runtime",
"@deepseek-ai/dsh-client-ui-command"
"@deepseek-ai/dsh-client-ui-command",
"@deepseek-ai/dsh-client-locale"
],
"platform": "web"
},
@@ -35,20 +37,35 @@
},
"license": "BSD-3-Clause",
"peerDependencies": {
"@deepseek-ai/dsh-client-connection": "^0.0.1",
"@deepseek-ai/dsh-client-locale": "^0.0.1",
"@deepseek-ai/dsh-client-runtime": "^0.0.1",
"@deepseek-ai/dsh-client-schema-form": "^0.0.1",
"@deepseek-ai/dsh-client-ui-command": "^0.0.1",
"@deepseek-ai/dsh-client-ui-primitives": "^0.0.1",
"@deepseek-ai/dsh-client-ui-slash": "^0.0.1",
"@deepseek-ai/dsh-client-ui-slots": "^0.0.1",
"@deepseek-ai/dsh-client-web-react": "^0.0.1",
"@deepseek-ai/dsh-invariants": "^0.0.1",
"@deepseek-ai/dsh-permission": "^0.0.1",
"cordis": "^4.0.0-rc.7"
"cordis": "^4.0.0-rc.7",
"react": "^18.2.0"
},
"devDependencies": {
"@deepseek-ai/dsh-client-connection": "workspace:^",
"@deepseek-ai/dsh-client-locale": "workspace:^",
"@deepseek-ai/dsh-client-runtime": "workspace:^",
"@deepseek-ai/dsh-client-schema-form": "workspace:^",
"@deepseek-ai/dsh-client-ui-command": "workspace:^",
"@deepseek-ai/dsh-client-ui-primitives": "workspace:^",
"@deepseek-ai/dsh-client-ui-slash": "workspace:^",
"@deepseek-ai/dsh-client-ui-slots": "workspace:^",
"@deepseek-ai/dsh-client-web-react": "workspace:^",
"@deepseek-ai/dsh-invariants": "workspace:^",
"@deepseek-ai/dsh-permission": "workspace:^",
"cordis": "^4.0.0-rc.7"
"@types/react": "~18.3.1",
"cordis": "^4.0.0-rc.7",
"react": "^18.2.0"
},
"files": [
"lib/index.js",

View File

@@ -0,0 +1,60 @@
/* Permission row: title/description plus the preset selector pill. */
.row {
display: flex;
align-items: center;
gap: 8px;
padding: 16px 0;
border-bottom: 1px solid var(--dsw-alias-border-l2);
}
.rowText {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
padding-right: 48px;
}
.title {
font-size: 14px;
font-weight: 400;
line-height: 22px;
color: var(--dsw-alias-label-primary);
}
.desc {
font-size: 12px;
font-weight: 400;
line-height: 18px;
color: var(--dsw-alias-label-tertiary);
}
.selector {
display: inline-flex;
align-items: center;
gap: 12px;
height: 36px;
padding: 0 14px;
border: none;
border-radius: 18px;
background: var(--dsw-alias-bg-module-platform);
font: inherit;
font-size: 14px;
line-height: 22px;
color: var(--dsw-alias-label-primary);
cursor: pointer;
}
.selector:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
}
.selector:disabled {
cursor: default;
}
.chevron {
flex: none;
}

View File

@@ -0,0 +1,88 @@
/**
* Permission preference row: the default preset for subsequently created
* sessions. Current-session switches remain on the composer `/permission`
* control.
*/
import { useEffect, useState } from 'react'
import type {
PropsLocale, PropsRuntime, SnapshotSelectorHook,
} from '@deepseek-ai/dsh-client-ui-slots'
import { IconChevronDownOutline14, Menu } from '@deepseek-ai/dsh-client-ui-primitives'
import type {
PermissionSettingsController, PermissionSettingsState,
} from './settings-store.ts'
import type { PermissionSettingsKey } from './locales.ts'
import css from './PermissionRow.module.css'
/** Injected controller and hook for the host-backed preference. */
export interface PermissionRowInjected {
/** Permission settings controller. */
controller: PermissionSettingsController
/** Selector hook bound to the controller snapshot. */
useSnapshot: SnapshotSelectorHook<PermissionSettingsState>
}
/** Full component props. */
export type PermissionRowProps =
PropsRuntime<'settings.general.item'> & PropsLocale<'settings.permission'> & PermissionRowInjected
/**
* Render the new-session Permission default selector.
* @param props - composed slot props.
* @returns the row, or null when the host does not expose permission settings.
*/
export function PermissionRow({ controller, useSnapshot, t }: PermissionRowProps) {
const state = useSnapshot(snapshot => snapshot)
const [open, setOpen] = useState(false)
useEffect(() => {
void controller.load()
}, [controller])
if (state.status === 'unavailable') return null
const selected = state.options.find(option => option.id === state.currentValue)
const busy = state.status === 'loading' || state.status === 'saving'
const label = selected?.label
?? (busy ? t('loading') : t('unavailable'))
const description: string = state.error ?? t('description')
return (
<div className={css.row}>
<div className={css.rowText}>
<div className={css.title}>{t('title')}</div>
<div className={css.desc} role={state.error === null ? undefined : 'alert'}>{description}</div>
</div>
<Menu
open={open}
onClose={() => { setOpen(false) }}
items={state.options.map(option => ({ id: option.id, label: option.label }))}
selectedId={state.currentValue}
onSelect={(id) => {
setOpen(false)
void controller.select(id)
}}
align="end"
portal
anchor={(
<button
type="button"
className={css.selector}
aria-haspopup="menu"
aria-expanded={open}
disabled={busy || !state.writable || state.options.length === 0}
onClick={() => { setOpen(value => !value) }}
>
{label}
<IconChevronDownOutline14 className={css.chevron} />
</button>
)}
/>
</div>
)
}
declare module '@deepseek-ai/dsh-client-ui-slots' {
interface LocaleNamespaceMap {
/** Permission row copy. */
'settings.permission': PermissionSettingsKey
}
}

View File

@@ -1,46 +1,46 @@
/**
* Permission preset plugin, browser half — a popupSelect DECORATION hung on
* the host `/permission` command: one flat list of presets, current value
* marked active, a pick executes the switch. The decoration owns only the
* bare invocation; the host command keeps its catalog row, the argued path
* (`/permission <preset>` still switches directly), and the lifecycle
* logging. Options and the active mark read the session's `permissions`
* projection (the same host-computed select the composer chip renders); a
* pick submits the `/permission <preset>` command line, so both surfaces
* write through one path and the pushed projection frame is the one
* confirmation.
* Permission plugin, browser half. The General-settings row writes the
* default preset for subsequently created sessions through Settings; the
* `/permission` popup decoration switches the current session through the
* host command and its `permissions` projection.
*/
import type { ClientContext, SessionFace } from '@deepseek-ai/dsh-client-runtime/client'
import type { CommandServiceContract, SelectOption } from '@deepseek-ai/dsh-client-ui-command/client'
import type { ClientSessionContext } from '@deepseek-ai/dsh-client-ui-slash/client'
import type { PermissionSelect } from '@deepseek-ai/dsh-permission/client'
import type { ConnectionHandle } from '@deepseek-ai/dsh-client-connection/client'
import { deferRegistration } from '@deepseek-ai/dsh-client-ui-slots'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
// Type-only: pulls the General item slot and locale service contracts.
import type {} from '@deepseek-ai/dsh-client-locale/client'
import { PermissionRow } from './PermissionRow.tsx'
import type { PermissionRowInjected } from './PermissionRow.tsx'
import { en, zh } from './locales.ts'
import { displayPresetName } from './presentation.ts'
import {
PERMISSION_SETTINGS_NS, PermissionSettingsController, refreshPermissionIfLoaded,
} from './settings-store.ts'
export type { PermissionRowInjected, PermissionRowProps } from './PermissionRow.tsx'
export type {
PermissionDefaultOption, PermissionSettingsState,
} from './settings-store.ts'
/** Required services (cordis fiber inject). */
export const inject = ['command', 'sessions']
export const inject = ['command', 'sessions', 'slots', 'locale', 'connection']
/** Read one session's current permissions projection value (undefined = capability absent). */
function selectOf(session: SessionFace | undefined): PermissionSelect | undefined {
return session?.projections.faceOf('permissions').getSnapshot() as PermissionSelect | undefined
}
/**
* Display transform twin of the composer chip's (ui-conversation
* PermissionSelect): kebab-case machine names render as title-case labels
* (`workspace-write` → `Workspace Write`) so both permission surfaces show
* the same text; non-kebab host-configured names pass through.
*/
function displayName(name: string): string {
if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) return name
return name.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
}
/** Flatten the projection select into popup rows; `custom` is display state, never a target. */
function optionsOf(value: PermissionSelect): SelectOption[] {
return value.options
.filter(option => option.value !== 'custom')
.map(option => ({
id: option.value,
label: displayName(option.name),
label: displayPresetName(option.name),
...(option.description !== undefined ? { detail: option.description } : {}),
...(option.value === value.currentValue ? { active: true } : {}),
}))
@@ -56,6 +56,41 @@ export function apply(ctx: ClientContext): void {
const sessions = ctx.sessions
const sessionFor = (session: ClientSessionContext): SessionFace | undefined =>
sessions.binding(session.sessionId)?.session
ctx.effect(() => ctx.locale.register('settings.permission', { zh, en }), 'ui-permission: settings row dictionaries')
const connection = ctx.get('connection') as ConnectionHandle
const controller = new PermissionSettingsController(connection.api)
const useSnapshot = bindSnapshotSelector(controller.store)
const injected = (): PermissionRowInjected => ({ controller, useSnapshot })
ctx.effect(() => {
const refresh = (ns?: string): void => {
if (ns !== undefined && ns !== PERMISSION_SETTINGS_NS) return
refreshPermissionIfLoaded(controller)
}
const disposers = [
ctx.on('settings/changed', refresh),
ctx.on('connection/reset', () => { refresh() }),
]
return () => {
controller.dispose()
for (const dispose of disposers) dispose()
}
}, 'ui-permission: settings invalidations')
ctx.effect(() => {
const row = deferRegistration(ctx.slots, 'settings.general.item', PermissionRow, () =>
ctx.slots.register({
name: 'settings.general.item',
id: 'permission',
order: -20,
locale: 'settings.permission',
inject: injected,
}, PermissionRow))
return () => { row.dispose() }
}, 'ui-permission: General settings row')
ctx.effect(() => command.decorate({
name: 'permission',
// The picker exists exactly while the projection does: a permission-less

View File

@@ -0,0 +1,20 @@
/** `settings.permission` namespace dictionaries (the Permission row's copy). */
/** Simplified Chinese dictionary (the key-set source of truth). */
export const zh = {
'title': '权限',
'description': '选择新会话的默认权限模式',
'loading': '加载中',
'unavailable': '不可用',
} satisfies Record<string, string>
/** The settings.permission namespace key union. */
export type PermissionSettingsKey = keyof typeof zh
/** English dictionary, checked complete against the zh key set. */
export const en = {
'title': 'Permission',
'description': 'Choose the default permission mode for new sessions',
'loading': 'Loading',
'unavailable': 'Unavailable',
} satisfies Record<PermissionSettingsKey, string>

View File

@@ -0,0 +1,9 @@
/**
* Convert conventional kebab-case preset names into user-facing title case.
* @param name - host-supplied preset label or key.
* @returns the title-cased conventional key, or a non-kebab label unchanged.
*/
export function displayPresetName(name: string): string {
if (!/^[a-z0-9]+(-[a-z0-9]+)*$/.test(name)) return name
return name.split('-').map(word => word.charAt(0).toUpperCase() + word.slice(1)).join(' ')
}

View File

@@ -0,0 +1,191 @@
/**
* Permission default-settings controller. The host descriptor supplies the
* current value and the dynamic preset enum; writes target only
* `defaultPreset` and carry the descriptor revision.
*/
import type {
IApiClient, SettingsNamespaceView,
} from '@deepseek-ai/dsh-client-connection/client'
import {
createSnapshotStore, type SnapshotStore,
} from '@deepseek-ai/dsh-client-runtime/client'
import {
nodeAtPath, rehydrateSchema, type SchemaNode,
} from '@deepseek-ai/dsh-client-schema-form'
import { displayPresetName } from './presentation.ts'
/** Permission's settings namespace on the host wire. */
export const PERMISSION_SETTINGS_NS = 'permission'
/** One selectable new-session default. */
export interface PermissionDefaultOption {
/** Preset key written to Settings. */
id: string
/** Host-supplied label or a title-cased preset key. */
label: string
}
/** Permission settings-row snapshot. */
export interface PermissionSettingsState {
status: 'idle' | 'loading' | 'ready' | 'saving' | 'unavailable' | 'error'
error: string | null
writable: boolean
currentValue: string
options: readonly PermissionDefaultOption[]
revision: number
}
interface ConstChoice {
type: string
value?: unknown
meta?: { description?: unknown }
}
/**
* Read the dynamic preset enum encoded by the host's `defaultPreset` schema.
* @param view - permission namespace descriptor.
* @returns current value and selectable options.
*/
export function permissionDefaultOf(view: SettingsNamespaceView): {
currentValue: string
options: PermissionDefaultOption[]
} {
const value = (view.value as { defaultPreset?: unknown } | null)?.defaultPreset
if (typeof value !== 'string') throw new Error('permission settings has no defaultPreset value')
const node = nodeAtPath(rehydrateSchema(view.schema), ['defaultPreset'])
if (node === undefined) throw new Error('permission settings schema has no defaultPreset field')
const rawChoices = node.type === 'union'
? (node.list as SchemaNode[] | undefined) ?? []
: [node]
const options = rawChoices.flatMap((candidate) => {
const choice = candidate as unknown as ConstChoice
if (choice.type !== 'const' || typeof choice.value !== 'string') return []
const described = choice.meta?.description
return [{
id: choice.value,
label: typeof described === 'string' && described.length > 0
? displayPresetName(described)
: displayPresetName(choice.value),
}]
})
if (options.length === 0 || !options.some(option => option.id === value)) {
throw new Error('permission settings schema does not advertise its current preset')
}
return { currentValue: value, options }
}
/** Controller joining Settings reads, writes, and pushed invalidations. */
export class PermissionSettingsController {
/** Row snapshot consumed through a bound selector hook. */
readonly store: SnapshotStore<PermissionSettingsState> = createSnapshotStore({
status: 'idle',
error: null,
writable: false,
currentValue: '',
options: [],
revision: 0,
})
private generation = 0
private view: SettingsNamespaceView | undefined
/** @param api - Settings wire face. */
constructor(private readonly api: Pick<IApiClient, 'settings'>) {}
/**
* Refresh the permission descriptor. Latest request wins.
* @returns nothing; {@link store} carries success or failure.
*/
async load(): Promise<void> {
const generation = ++this.generation
this.store.update((state) => {
state.status = 'loading'
state.error = null
})
try {
const response = await this.api.settings.describe({})
if (!response.result.ok) throw new Error(response.result.error.message)
if (generation !== this.generation) return
const view = response.result.value.namespaces.find(entry => entry.ns === PERMISSION_SETTINGS_NS)
if (view === undefined) {
this.view = undefined
this.store.update((state) => {
state.status = 'unavailable'
state.writable = false
state.currentValue = ''
state.options = []
})
return
}
this.accept(view, response.result.value.writable)
} catch (error) {
if (generation !== this.generation) return
this.fail(error)
}
}
/**
* Persist one preset as the default for subsequently created sessions.
* @param preset - advertised preset key.
* @returns nothing; {@link store} carries success or failure.
*/
async select(preset: string): Promise<void> {
const view = this.view
const state = this.store.getSnapshot()
if (view === undefined || !state.writable) return
const generation = ++this.generation
this.store.update((draft) => {
draft.status = 'saving'
draft.error = null
})
try {
const response = await this.api.settings.mutate({
ns: PERMISSION_SETTINGS_NS,
ops: [{ op: 'set', path: ['defaultPreset'], value: preset }],
expectedRevision: view.revision,
})
if (generation !== this.generation) return
if (!response.result.ok) throw new Error(response.result.error.message)
this.accept(response.result.value, true)
} catch (error) {
if (generation !== this.generation) return
this.fail(error)
}
}
/** Stop in-flight responses from publishing after plugin disposal. */
dispose(): void {
this.generation += 1
this.view = undefined
}
private accept(view: SettingsNamespaceView, writable: boolean): void {
const resolved = permissionDefaultOf(view)
this.view = view
this.store.update((state) => {
state.status = 'ready'
state.error = null
state.writable = writable
state.currentValue = resolved.currentValue
state.options = resolved.options
state.revision = view.revision
})
}
private fail(error: unknown): void {
this.store.update((state) => {
state.status = 'error'
state.error = error instanceof Error ? error.message : String(error)
})
}
}
/**
* Refetch only after the row has opened once.
* @param controller - permission settings controller.
*/
export function refreshPermissionIfLoaded(controller: PermissionSettingsController): void {
if (controller.store.getSnapshot().status === 'idle') return
void controller.load()
}

View File

@@ -0,0 +1,4 @@
declare module '*.module.css' {
const classes: Record<string, string>
export default classes
}

View File

@@ -1,8 +1,8 @@
/**
* Permission preset selection plugin, node half. Pure UI plugin: the empty
* apply exists so the plugin appears in the host cordis.yml / Loader; the
* browser half ships via exports["./client"], discovered through the
* package.json dshClient declaration.
* Permission surfaces plugin, node half. The empty apply exists so the plugin
* appears in the host cordis.yml / Loader; the browser half ships the
* new-session Settings row and current-session command picker through
* exports["./client"], discovered from the package.json dshClient declaration.
*/
/** Host plugin body — no host-side behavior for this surface plugin. */

View File

@@ -15,9 +15,9 @@ export const name = 'client-ui-permission-invariant'
export const inject = ['invariants']
/**
* No runtime invariant: a single command contribution registration whose disposal is
* proven by the HMR-safety spec — it emits no cordis events and owns no
* cross-plugin mutable state.
* No runtime invariant: the command and slot contribution lifecycles are
* proven by the HMR-safety spec, while the browser-only Settings controller
* owns no host events or cross-plugin mutable state.
*/
const install: InvariantInstaller = () => {}

View File

@@ -5,13 +5,16 @@
* the current value active and `custom` excluded; availability follows the
* projection key's presence; a pick submits the /permission line through
* Session.command and surfaces rejection/unmatched as thrown errors; fiber
* disposal removes the contribution (HMR safety).
* disposal removes the contribution (HMR safety). The same plugin registers
* its Settings row and invalidates that row on host settings changes.
*/
import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
import type { SessionId } from '@deepseek-ai/dsh-client-runtime/client'
import { SlotsService, type SessionId } from '@deepseek-ai/dsh-client-runtime/client'
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
import type { CommandDecoration } from '@deepseek-ai/dsh-client-ui-command/client'
import type { PermissionSelect } from '@deepseek-ai/dsh-permission/client'
import { PermissionRow } from '../src/client/PermissionRow.tsx'
import { apply, inject } from '../src/client/index.ts'
const sid = (k: string): SessionId => k as SessionId
@@ -27,6 +30,26 @@ const SELECT: PermissionSelect = {
async function bench() {
const ctx = new Context()
await ctx.plugin(SlotsService)
const locale = new LocaleService(ctx)
ctx.provide('locale', locale)
ctx.slots.register({
name: 'root',
children: {
'settings.general.item': { kind: 'list', scope: 'root' },
},
} as never, () => null)
ctx.provide('connection', {
api: {
settings: {
describe: () => Promise.resolve({
rpcId: 'describe',
result: { ok: true as const, value: { writable: true, namespaces: [] } },
}),
mutate: () => Promise.reject(new Error('settings mutation is not exercised')),
},
},
} as never)
let decoration: CommandDecoration | undefined
ctx.provide('command', {
decorate(c: CommandDecoration) {
@@ -60,6 +83,8 @@ async function bench() {
ctx, fiber, values, commands,
setResult: (r: { ok: boolean; matched?: boolean }) => { commandResult = r },
decoration: () => decoration,
permissionRow: () => ctx.slots.entries('settings.general.item')
.find(entry => entry.component === PermissionRow),
}
}
@@ -69,6 +94,11 @@ describe('ui-permission browser plugin', () => {
const c = b.decoration()!
expect(c.name).toBe('permission')
expect(c.ui.kind).toBe('popupSelect')
const row = b.permissionRow()!
expect(row.options).toEqual({ id: 'permission', order: -20 })
const injected = row.inject?.()
expect(injected?.controller).toBeDefined()
expect(typeof injected?.useSnapshot).toBe('function')
})
it('availability follows the projection key; options mark the current value active and exclude custom', async () => {
@@ -114,7 +144,11 @@ describe('ui-permission browser plugin', () => {
it('disposal removes the decoration (HMR safety)', async () => {
const b = await bench()
expect(b.decoration()).toBeDefined()
b.ctx.emit('settings/changed', 'another')
b.ctx.emit('settings/changed', 'permission')
b.ctx.emit('connection/reset')
await b.fiber.dispose()
expect(b.decoration()).toBeUndefined()
expect(b.permissionRow()).toBeUndefined()
})
})

View File

@@ -0,0 +1,127 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { bindSnapshotSelector } from '@deepseek-ai/dsh-client-web-react'
import type { SettingsNamespaceView } from '@deepseek-ai/dsh-client-connection/client'
import { PermissionRow, type PermissionRowProps } from '../src/client/PermissionRow.tsx'
import { en } from '../src/client/locales.ts'
import { PermissionSettingsController } from '../src/client/settings-store.ts'
afterEach(cleanup)
const SCHEMA = {
uid: 4,
refs: {
1: { type: 'const', value: 'read-only' },
2: { type: 'const', value: 'workspace-write' },
3: { type: 'union', list: [1, 2] },
4: { type: 'object', dict: { defaultPreset: 3 } },
},
}
function view(defaultPreset: string, revision = 0): SettingsNamespaceView {
return {
ns: 'permission',
schema: SCHEMA,
value: { defaultPreset },
base: { defaultPreset: 'read-only' },
applies: 'live',
secrets: [],
revision,
}
}
function ok<T>(value: T) {
return { rpcId: 'test', result: { ok: true as const, value } }
}
const dictionary: Record<string, string> = en
const t: PermissionRowProps['t'] = key => dictionary[key] ?? key
const runtime = {
useSessions: (() => { throw new Error('unused') }) as never,
useWorkspaces: (() => { throw new Error('unused') }) as never,
}
function mount(controller: PermissionSettingsController) {
return render(
<PermissionRow
{...runtime}
controller={controller}
useSnapshot={bindSnapshotSelector(controller.store)}
t={t}
/>,
)
}
describe('PermissionRow', () => {
it('loads the descriptor, opens the menu, and selects a new default', async () => {
const mutate = vi.fn(() => Promise.resolve(ok(view('workspace-write', 1))))
const controller = new PermissionSettingsController({
settings: {
describe: () => Promise.resolve(ok({ writable: true, namespaces: [view('read-only')] })),
mutate,
} as never,
})
mount(controller)
const button = await screen.findByRole('button', { name: 'Read Only' })
expect(button.getAttribute('aria-expanded')).toBe('false')
fireEvent.click(button)
expect(button.getAttribute('aria-expanded')).toBe('true')
fireEvent.keyDown(document, { key: 'Escape' })
await waitFor(() => { expect(button.getAttribute('aria-expanded')).toBe('false') })
fireEvent.click(button)
fireEvent.click(button)
expect(button.getAttribute('aria-expanded')).toBe('false')
fireEvent.click(button)
fireEvent.click(screen.getByRole('menuitem', { name: 'Workspace Write' }))
await screen.findByRole('button', { name: 'Workspace Write' })
expect(mutate).toHaveBeenCalledOnce()
})
it('hides an unavailable namespace and disables a read-only provider', async () => {
const absent = new PermissionSettingsController({
settings: {
describe: () => Promise.resolve(ok({ writable: true, namespaces: [] })),
mutate: vi.fn(),
} as never,
})
const rendered = mount(absent)
await waitFor(() => { expect(rendered.container.textContent).toBe('') })
rendered.unmount()
const readonly = new PermissionSettingsController({
settings: {
describe: () => Promise.resolve(ok({ writable: false, namespaces: [view('read-only')] })),
mutate: vi.fn(),
} as never,
})
mount(readonly)
expect((await screen.findByRole('button', { name: 'Read Only' })).hasAttribute('disabled')).toBe(true)
})
it('shows loading and a contained write error', async () => {
const describe = Promise.withResolvers<ReturnType<typeof ok<{
writable: boolean
namespaces: SettingsNamespaceView[]
}>>>()
const controller = new PermissionSettingsController({
settings: {
describe: () => describe.promise,
mutate: () => Promise.resolve({
rpcId: 'test',
result: {
ok: false as const,
error: { code: 'settings-conflict', message: 'changed elsewhere', details: {} },
},
}),
} as never,
})
mount(controller)
expect((await screen.findByRole('button', { name: 'Loading' })).hasAttribute('disabled')).toBe(true)
describe.resolve(ok({ writable: true, namespaces: [view('read-only')] }))
const button = await screen.findByRole('button', { name: 'Read Only' })
fireEvent.click(button)
fireEvent.click(screen.getByRole('menuitem', { name: 'Workspace Write' }))
expect((await screen.findByRole('alert')).textContent).toBe('changed elsewhere')
})
})

View File

@@ -0,0 +1,254 @@
import { describe, expect, it, vi } from 'vitest'
import type { SettingsNamespaceView } from '@deepseek-ai/dsh-client-connection/client'
import {
PermissionSettingsController, permissionDefaultOf, refreshPermissionIfLoaded,
} from '../src/client/settings-store.ts'
const SCHEMA = {
uid: 6,
refs: {
1: { type: 'const', value: 'read-only' },
2: { type: 'const', meta: { description: 'Workspace' }, value: 'workspace-write' },
3: { type: 'union', list: [1, 2] },
6: { type: 'object', dict: { defaultPreset: 3 } },
},
}
function view(defaultPreset: string, revision = 0, schema: SettingsNamespaceView['schema'] = SCHEMA): SettingsNamespaceView {
return {
ns: 'permission',
schema,
value: { defaultPreset },
base: { defaultPreset: 'read-only' },
applies: 'live',
secrets: [],
revision,
}
}
function ok<T>(value: T) {
return { rpcId: 'test', result: { ok: true as const, value } }
}
describe('permission settings store', () => {
it('derives dynamic options and host labels from the descriptor schema', () => {
expect(permissionDefaultOf(view('read-only'))).toEqual({
currentValue: 'read-only',
options: [
{ id: 'read-only', label: 'Read Only' },
{ id: 'workspace-write', label: 'Workspace' },
],
})
const single = {
uid: 2,
refs: {
1: { type: 'const', meta: { description: '' }, value: 'read-only' },
2: { type: 'object', dict: { defaultPreset: 1 } },
},
}
expect(permissionDefaultOf(view('read-only', 0, single))).toEqual({
currentValue: 'read-only',
options: [{ id: 'read-only', label: 'Read Only' }],
})
const undescribed = {
uid: 2,
refs: {
1: { type: 'const', meta: { description: 7 }, value: 'read-only' },
2: { type: 'object', dict: { defaultPreset: 1 } },
},
}
expect(permissionDefaultOf(view('read-only', 0, undescribed)).options)
.toEqual([{ id: 'read-only', label: 'Read Only' }])
})
it('rejects malformed values and dynamic enums at the wire boundary', () => {
expect(() => permissionDefaultOf({ ...view('read-only'), value: {} })).toThrow(/no defaultPreset value/)
expect(() => permissionDefaultOf(view('read-only', 0, {
uid: 1, refs: { 1: { type: 'object', dict: {} } },
}))).toThrow(/no defaultPreset field/)
expect(() => permissionDefaultOf(view('read-only', 0, {
uid: 2,
refs: {
1: { type: 'union' },
2: { type: 'object', dict: { defaultPreset: 1 } },
},
}))).toThrow(/does not advertise/)
expect(() => permissionDefaultOf(view('read-only', 0, {
uid: 4,
refs: {
1: { type: 'string' },
2: { type: 'const', value: 1 },
3: { type: 'union', list: [1, 2] },
4: { type: 'object', dict: { defaultPreset: 3 } },
},
}))).toThrow(/does not advertise/)
expect(() => permissionDefaultOf(view('missing'))).toThrow(/does not advertise/)
})
it('loads and writes defaultPreset with optimistic concurrency', async () => {
const describe = vi.fn(() => Promise.resolve(ok({
writable: true,
namespaces: [view('read-only', 4)],
})))
const mutate = vi.fn(() => Promise.resolve(ok(view('workspace-write', 5))))
const controller = new PermissionSettingsController({
settings: { describe, mutate } as never,
})
await controller.load()
expect(controller.store.getSnapshot()).toMatchObject({
status: 'ready',
writable: true,
currentValue: 'read-only',
revision: 4,
})
await controller.select('workspace-write')
expect(mutate).toHaveBeenCalledWith({
ns: 'permission',
ops: [{ op: 'set', path: ['defaultPreset'], value: 'workspace-write' }],
expectedRevision: 4,
})
expect(controller.store.getSnapshot()).toMatchObject({
status: 'ready',
currentValue: 'workspace-write',
revision: 5,
})
})
it('hides the row when the namespace is absent and contains write failures', async () => {
const describe = vi.fn(() => Promise.resolve(ok({ writable: true, namespaces: [] })))
const controller = new PermissionSettingsController({
settings: { describe, mutate: vi.fn() } as never,
})
await controller.load()
expect(controller.store.getSnapshot().status).toBe('unavailable')
const failing = new PermissionSettingsController({
settings: {
describe: () => Promise.resolve(ok({ writable: true, namespaces: [view('read-only')] })),
mutate: () => Promise.resolve({
rpcId: 'test',
result: {
ok: false as const,
error: { code: 'settings-conflict', message: 'stale', details: {} },
},
}),
} as never,
})
await failing.load()
await failing.select('workspace-write')
expect(failing.store.getSnapshot()).toMatchObject({ status: 'error', error: 'stale' })
})
it('contains read failures, no-ops without a writable view, and ignores stale responses', async () => {
const first = Promise.withResolvers<ReturnType<typeof ok<{
writable: boolean
namespaces: SettingsNamespaceView[]
}>>>()
const describe = vi.fn()
.mockImplementationOnce(() => first.promise)
.mockResolvedValueOnce(ok({ writable: false, namespaces: [view('read-only', 2)] }))
const mutate = vi.fn()
const controller = new PermissionSettingsController({
settings: { describe, mutate } as never,
})
const stale = controller.load()
await controller.load()
first.resolve(ok({ writable: true, namespaces: [view('workspace-write', 1)] }))
await stale
expect(controller.store.getSnapshot()).toMatchObject({
currentValue: 'read-only',
writable: false,
revision: 2,
})
await controller.select('workspace-write')
expect(mutate).not.toHaveBeenCalled()
const rejected = new PermissionSettingsController({
settings: {
describe: () => Promise.resolve({
rpcId: 'test',
result: { ok: false as const, error: { code: 'internal', message: 'offline', details: {} } },
}),
mutate,
} as never,
})
await rejected.select('workspace-write')
await rejected.load()
expect(rejected.store.getSnapshot()).toMatchObject({ status: 'error', error: 'offline' })
const thrown = new PermissionSettingsController({
settings: {
// Promise consumers must contain unknown rejection values from a
// transport implementation, including non-Error legacy clients.
// oxlint-disable-next-line typescript/prefer-promise-reject-errors
describe: () => Promise.reject('disconnected'),
mutate,
} as never,
})
await thrown.load()
expect(thrown.store.getSnapshot()).toMatchObject({ status: 'error', error: 'disconnected' })
})
it('disposal suppresses in-flight reads and writes, and loaded invalidations refetch', async () => {
const read = Promise.withResolvers<ReturnType<typeof ok<{
writable: boolean
namespaces: SettingsNamespaceView[]
}>>>()
const describe = vi.fn(() => read.promise)
const idle = new PermissionSettingsController({ settings: { describe, mutate: vi.fn() } as never })
refreshPermissionIfLoaded(idle)
expect(describe).not.toHaveBeenCalled()
const loading = idle.load()
idle.dispose()
read.resolve(ok({ writable: true, namespaces: [view('read-only')] }))
await loading
expect(idle.store.getSnapshot().status).toBe('loading')
const rejectedRead = Promise.withResolvers<ReturnType<typeof ok<{
writable: boolean
namespaces: SettingsNamespaceView[]
}>>>()
const disposedRead = new PermissionSettingsController({
settings: { describe: () => rejectedRead.promise, mutate: vi.fn() } as never,
})
const reading = disposedRead.load()
disposedRead.dispose()
rejectedRead.reject(new Error('late read'))
await reading
expect(disposedRead.store.getSnapshot().status).toBe('loading')
const mutation = Promise.withResolvers<ReturnType<typeof ok<SettingsNamespaceView>>>()
const activeDescribe = vi.fn(() => Promise.resolve(ok({
writable: true,
namespaces: [view('read-only')],
})))
const active = new PermissionSettingsController({
settings: {
describe: activeDescribe,
mutate: () => mutation.promise,
} as never,
})
await active.load()
refreshPermissionIfLoaded(active)
await vi.waitFor(() => { expect(activeDescribe).toHaveBeenCalledTimes(2) })
const saving = active.select('workspace-write')
active.dispose()
mutation.resolve(ok(view('workspace-write', 1)))
await saving
expect(active.store.getSnapshot().status).toBe('saving')
const rejectedMutation = Promise.withResolvers<ReturnType<typeof ok<SettingsNamespaceView>>>()
const disposedWrite = new PermissionSettingsController({
settings: {
describe: () => Promise.resolve(ok({ writable: true, namespaces: [view('read-only')] })),
mutate: () => rejectedMutation.promise,
} as never,
})
await disposedWrite.load()
const writing = disposedWrite.select('workspace-write')
disposedWrite.dispose()
rejectedMutation.reject(new Error('late write'))
await writing
expect(disposedWrite.store.getSnapshot().status).toBe('saving')
})
})

View File

@@ -8,18 +8,36 @@
"src"
],
"references": [
{
"path": "../connection"
},
{
"path": "../locale"
},
{
"path": "../../../vendor/cordis"
},
{
"path": "../runtime"
},
{
"path": "../schema-form"
},
{
"path": "../ui-command"
},
{
"path": "../ui-primitives"
},
{
"path": "../ui-slash"
},
{
"path": "../ui-slots"
},
{
"path": "../web-react"
},
{
"path": "../../ui/permission"
},

View File

@@ -1,6 +1,6 @@
# Bilingual-pair consistency record (docs/i18n/README.md): the git blob hash of each
# 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
README.md: c392d745021c0fc6a752cf71dd0506a435106c50
README.zh.md: 83ab81e01eae435a74b50fa363a4de203c483002
# pnpm run verify-translation-pairing --write packages/client/ui-settings-general/README.md
README.md: 9e12f02fc1e767fb807be4fdd3f506c189662bc7
README.zh.md: 225e27f5705f33bc6199615b0fe96e04eaa6a04c

View File

@@ -2,7 +2,7 @@
English | [中文](README.zh.md)
Settings ownerless-copy plugin: registers everything on the Settings surface that belongs to no single feature — the shell's trigger/header/close chrome content, the General section (Permission/Tool Call skeleton rows + the `settings.general.item` slot declaration), and the `settings` dictionaries. Feature-owned rows (Language, Appearance) and sections (Models) stay with their feature packages.
Settings ownerless-copy plugin: registers everything on the Settings surface that belongs to no single feature — the shell's trigger/header/close chrome content, the General section (`settings.general.item` slot plus the Tool Call skeleton), and the `settings` dictionaries. Feature-owned rows (Permission, Language, Appearance) and sections (Models) stay with their feature packages.
## Model Experience
@@ -14,4 +14,4 @@ None; this package neither assembles nor sends a provider request.
## Known Limitations and Deferred Work
- **Permission and Tool Call are display skeletons** — the backing host services and RPC methods do not exist yet; the controls are disabled and write nothing. When they gain real backing, each moves to its owning feature plugin per the self-registration doctrine.
- **Tool Call is a display skeleton** — its backing host setting does not exist yet, so the cubes write nothing. When it gains real backing, the row moves to its owning feature plugin per the self-registration doctrine.

View File

@@ -2,7 +2,7 @@
[English](README.md) | 中文
设置界面文案插件:在设置界面注册所有不属于单一功能的内容,包括外壳的触发器、标题栏与关闭控件内容,「通用」分区(「权限」/「工具调用」骨架行和 `settings.general.item` slot 声明),以及 `settings` 字典。归具体功能所有的行(「语言」、「外观」)和分区(「模型」)仍由各自的功能包提供。
设置界面无归属文案插件:在设置界面注册所有不属于单一功能的内容,包括外壳的触发器、标题栏与关闭控件内容,「通用」分区(`settings.general.item` slot 加上「工具调用」骨架行),以及 `settings` 字典。归具体功能所有的行(「权限」、「语言」、「外观」)和分区(「模型」)仍由各自的功能包提供。
## 模型体验
@@ -14,4 +14,4 @@
## 已知限制与暂缓事项
- **「权限」与「工具调用」只是展示骨架**:对应的宿主服务和 RPC 方法尚不存在;这些控件已禁用,不会写入任何内容。一旦获得实际支撑,按照自注册原则,每一项都会移至拥有它的功能插件。
- **「工具调用」只是展示骨架**:其宿主设置尚不存在,因此控件不会写入任何内容。一旦获得实际支撑,按照自注册原则,该行会移至拥有它的功能插件。

View File

@@ -1,6 +1,6 @@
{
"name": "@deepseek-ai/dsh-client-ui-settings-general",
"description": "Settings ownerless-copy plugin: the General section (skeleton rows + item slot), the shell trigger/header chrome content, and the settings dictionaries",
"description": "Settings ownerless-copy plugin: the General section and Tool Call skeleton, shell trigger/header chrome content, and settings dictionaries",
"version": "0.0.1",
"private": true,
"type": "module",

View File

@@ -13,15 +13,6 @@
border-bottom: none;
}
/* Title + trailing control row (figma 'Setting-Cell': gap 8, pad 16/0). */
.row {
display: flex;
align-items: center;
gap: 8px;
padding: 16px 0;
border-bottom: 1px solid var(--dsw-alias-border-l2);
}
/* Title + full-width body group (figma 'Frame 2117131229': column, gap 8). */
.group {
display: flex;
@@ -31,16 +22,6 @@
border-bottom: 1px solid var(--dsw-alias-border-l2);
}
/* Leading text column (figma 'Frame 2036083120': gap 4, pad-right 48). */
.rowText {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
gap: 4px;
padding-right: 48px;
}
.title {
font-size: 14px;
font-weight: 400;
@@ -55,35 +36,6 @@
color: var(--dsw-alias-label-tertiary);
}
/* Selector pill (figma 'Selector': h36 r18, fill #F5F6F7, pad 0/14, gap 12). */
.selector {
display: inline-flex;
align-items: center;
gap: 12px;
height: 36px;
padding: 0 14px;
border: none;
border-radius: 18px;
background: var(--dsw-alias-bg-module-platform);
font: inherit;
font-size: 14px;
line-height: 22px;
color: var(--dsw-alias-label-primary);
cursor: pointer;
}
.selector:hover:not(:disabled) {
background: var(--dsw-alias-interactive-bg-hover);
}
.selector:disabled {
cursor: default;
}
.chevron {
flex: none;
}
/* Tool Call mode cubes share an 8px gap and wrap to one per row when the
panel is too narrow. */
.cubeRow {

View File

@@ -1,55 +1,51 @@
/**
* The General section (figma 501:29983 'Options'): Permission and Tool Call
* skeleton rows, then the feature-contributed preference rows from the
* `settings.general.item` slot (locale → Language, ui-theme → Appearance).
* The section column stacks rows; each row draws its own internals and
* separator.
* The General section (figma 501:29983 'Options'): one column rendering the
* `settings.general.item` contributions. Features own their rows; this
* package contributes only the ownerless Tool Call skeleton.
*/
import { IconChevronDownOutline14 } from '@deepseek-ai/dsh-client-ui-primitives'
import type { PropsLocale, PropsRenderSlots, PropsRuntime } from '@deepseek-ai/dsh-client-ui-slots'
import css from './GeneralSection.module.css'
/** Full component props: section owner share + item render share + the standard locale seat. */
/** Full component props: section owner share plus item render share. */
export type GeneralSectionComponentProps =
PropsRuntime<'settings.section'> & PropsRenderSlots<'settings.general.item'> & PropsLocale<'settings'>
PropsRuntime<'settings.section'> & PropsRenderSlots<'settings.general.item'>
/**
* Render the General section content column.
* @param props - composed slot props (contract/slots.ts).
* @returns the section element tree.
*/
export function GeneralSection({ t, renderSlot }: GeneralSectionComponentProps) {
export function GeneralSection({ renderSlot }: GeneralSectionComponentProps) {
return (
<div className={css.section}>
{/* Permission (skeleton): disabled selector pill. */}
<div className={css.row}>
<div className={css.rowText}>
<div className={css.title}>{t('permission.title')}</div>
<div className={css.desc}>{t('permission.desc')}</div>
</div>
<button type="button" className={css.selector} disabled>
{t('permission.value')}
<IconChevronDownOutline14 className={css.chevron} />
</button>
</div>
{/* Tool Call (skeleton): schema cube pinned selected, code cube unselected. */}
<div className={css.group}>
<div className={css.title}>{t('toolcall.title')}</div>
<div className={css.cubeRow}>
<div className={`${css.modeCube} ${css.selected}`}>
<div className={css.title}>{t('toolcall.schema.title')}</div>
<div className={css.desc}>{t('toolcall.schema.desc')}</div>
</div>
<div className={css.modeCube}>
<div className={css.title}>{t('toolcall.code.title')}</div>
<div className={css.desc}>{t('toolcall.code.desc')}</div>
</div>
</div>
</div>
{/* Feature-owned preference rows (Language, Appearance, …). */}
{renderSlot('settings.general.item', {})}
</div>
)
}
/** Props of the ownerless Tool Call item contribution. */
export type ToolCallSkeletonProps =
PropsRuntime<'settings.general.item'> & PropsLocale<'settings'>
/**
* Render the static Tool Call mode choice until its host setting exists.
* @param props - item runtime and translated copy.
* @returns the skeleton row.
*/
export function ToolCallSkeleton({ t }: ToolCallSkeletonProps) {
return (
<div className={css.group}>
<div className={css.title}>{t('toolcall.title')}</div>
<div className={css.cubeRow}>
<div className={`${css.modeCube} ${css.selected}`}>
<div className={css.title}>{t('toolcall.schema.title')}</div>
<div className={css.desc}>{t('toolcall.schema.desc')}</div>
</div>
<div className={css.modeCube}>
<div className={css.title}>{t('toolcall.code.title')}</div>
<div className={css.desc}>{t('toolcall.code.desc')}</div>
</div>
</div>
</div>
)
}

View File

@@ -1,9 +1,9 @@
/**
* Settings ownerless-copy plugin, browser half: registers everything on the
* Settings surface that belongs to no single feature — the trigger/header
* chrome content, the General section (skeleton rows + the
* `settings.general.item` slot declaration), and the `settings`
* dictionaries. Feature-owned rows and sections stay with their features.
* chrome content, the General section (`settings.general.item` slot plus the
* ownerless Tool Call skeleton), and the `settings` dictionaries.
* Feature-owned rows and sections stay with their features.
* Export discipline: packages/client/AGENTS.md.
*/
import type { ClientContext } from '@deepseek-ai/dsh-client-runtime/client'
@@ -13,13 +13,15 @@ import type {} from '@deepseek-ai/dsh-client-ui-settings/client'
// Type-only: pulls ctx.locale and the 'settings.general.item' SlotMap merge.
import type {} from '@deepseek-ai/dsh-client-locale/client'
import { CloseLabel, HeaderContent, TriggerContent } from './chrome.tsx'
import { GeneralSection } from './GeneralSection.tsx'
import { GeneralSection, ToolCallSkeleton } from './GeneralSection.tsx'
import { en, zh, type SettingsKey } from './locales.ts'
export type {
CloseLabelProps, HeaderContentProps, TriggerContentProps,
} from './chrome.tsx'
export type { GeneralSectionComponentProps } from './GeneralSection.tsx'
export type {
GeneralSectionComponentProps, ToolCallSkeletonProps,
} from './GeneralSection.tsx'
export type { SettingsKey } from './locales.ts'
declare module '@deepseek-ai/dsh-client-ui-slots' {
@@ -67,11 +69,19 @@ export function apply(ctx: ClientContext): void {
locale: NS,
children: { 'settings.general.item': { kind: 'list', scope: 'root' } },
}, GeneralSection))
const toolCall = deferRegistration(ctx.slots, 'settings.general.item', ToolCallSkeleton, () =>
ctx.slots.register({
name: 'settings.general.item',
id: 'tool-call',
order: -10,
locale: NS,
}, ToolCallSkeleton))
return () => {
trigger.dispose()
header.dispose()
close.dispose()
general.dispose()
toolCall.dispose()
}
}, 'ui-settings-general: chrome and section registrations')
}

View File

@@ -1,12 +1,10 @@
/**
* `settings` namespace dictionaries: shell chrome plus the shell-owned
* General section (nav label, skeleton rows). Skeleton-row technical copy
* (Read only / Schema mode / Code mode and their descriptions) is shared
* verbatim across locales per the Figma design. Feature-owned rows
* (Language, Appearance) ship their copy in their own packages.
* General section (nav label and ownerless Tool Call skeleton). Technical
* mode copy is shared verbatim across locales per the Figma design.
* Feature-owned rows ship their copy in their own packages.
*/
const SHARED = {
'permission.value': 'Read only',
'toolcall.schema.title': 'Schema mode',
'toolcall.schema.desc': 'Traditional function calling — invoke tools one at a time',
'toolcall.code.title': 'Code mode',
@@ -20,8 +18,6 @@ export const zh = {
'title': '设置',
'close': '关闭',
'general.nav': '通用设置',
'permission.title': '权限',
'permission.desc': '选择默认权限模式',
'toolcall.title': '工具调用',
} satisfies Record<string, string>
@@ -35,7 +31,5 @@ export const en = {
'title': 'Settings',
'close': 'Close',
'general.nav': 'General',
'permission.title': 'Permission',
'permission.desc': 'Choose default permission mode',
'toolcall.title': 'Tool Call',
} satisfies Record<SettingsKey, string>

View File

@@ -1,12 +1,12 @@
/** Ownerless-copy registrations: the four seats, the dictionaries, thunked labels, and HMR recovery. */
import { Context } from 'cordis'
import { describe, expect, it } from 'vitest'
import { describe, expect, it, vi } from 'vitest'
import { resolveSlotLabel } from '@deepseek-ai/dsh-client-ui-slots'
import { SlotsService } from '@deepseek-ai/dsh-client-runtime/client'
import { LocaleService } from '@deepseek-ai/dsh-client-locale/client'
import { apply, inject } from '@deepseek-ai/dsh-client-ui-settings-general/client'
import { CloseLabel, HeaderContent, TriggerContent } from '../src/client/chrome.tsx'
import { GeneralSection } from '../src/client/GeneralSection.tsx'
import { GeneralSection, ToolCallSkeleton } from '../src/client/GeneralSection.tsx'
/** The four seats this plugin fills (slot name → expected component). */
const SEATS = [
@@ -61,10 +61,16 @@ describe('ui-settings-general apply', () => {
// The nav label is a locale-following thunk; owners resolve at read time.
expect(resolveSlotLabel(entry.options.label)).toBe('通用设置')
expect(before.slots.spec('settings.general.item')).toEqual({ kind: 'list', scope: 'root' })
const toolEntry = before.slots.entries('settings.general.item')[0]!
expect(toolEntry).toMatchObject({
component: ToolCallSkeleton,
options: { id: 'tool-call', order: -10 },
})
// Copy rides the standard locale seat: every seat declares the namespace.
for (const [name] of SEATS) {
expect(before.slots.entries(name)[0]!.locale).toBe('settings')
}
expect(toolEntry.locale).toBe('settings')
const after = await bench()
await after.ctx.plugin({ inject: [...inject], apply }).await()
@@ -76,6 +82,9 @@ describe('ui-settings-general apply', () => {
// The self-inflicted ledger notifications hit the duplicate guard.
expect(after.slots.entries(name)).toHaveLength(1)
}
await vi.waitFor(() => {
expect(after.slots.entries('settings.general.item')[0]!.component).toBe(ToolCallSkeleton)
})
})
it('registers the zh/en settings dictionaries and frees the seats on teardown', async () => {
@@ -124,6 +133,7 @@ describe('ui-settings-general apply', () => {
for (const [name, component] of SEATS) {
expect(b.slots.entries(name)[0]!.component).toBe(component)
}
expect(b.slots.entries('settings.general.item')[0]!.component).toBe(ToolCallSkeleton)
expect(b.slots.spec('settings.general.item')).toEqual({ kind: 'list', scope: 'root' })
// The recovered registrations still ride the locale path.
b.locale.setLocale('en')

View File

@@ -1,8 +1,10 @@
// @vitest-environment jsdom
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import type { GeneralSectionComponentProps } from '../src/client/GeneralSection.tsx'
import { GeneralSection } from '../src/client/GeneralSection.tsx'
import type {
GeneralSectionComponentProps, ToolCallSkeletonProps,
} from '../src/client/GeneralSection.tsx'
import { GeneralSection, ToolCallSkeleton } from '../src/client/GeneralSection.tsx'
import { CloseLabel, HeaderContent, TriggerContent } from '../src/client/chrome.tsx'
import { en } from '../src/client/locales.ts'
@@ -10,7 +12,7 @@ afterEach(cleanup)
// The seat's key domain is settings ∪ common; the stub answers from the
// package dictionary and falls back to the key like the real chain.
const t: GeneralSectionComponentProps['t'] = key => (en as Record<string, string>)[key] ?? key
const t: ToolCallSkeletonProps['t'] = key => (en as Record<string, string>)[key] ?? key
// Global standard kit stubs: none of these components consume the hooks.
const unusedHook = (() => { throw new Error('unused by settings-general components') }) as never
@@ -42,21 +44,21 @@ describe('GeneralSection', () => {
const renderSlot = vi.fn(
((key: string) => <div data-testid={`slot-${key}`} />) as GeneralSectionComponentProps['renderSlot'],
)
const props: GeneralSectionComponentProps = { ...kit, t, renderSlot }
const props: GeneralSectionComponentProps = { ...kit, renderSlot }
const view = render(<GeneralSection {...props} />)
return { view, renderSlot }
}
it('renders the Permission skeleton row with the disabled selector', () => {
mount()
expect(screen.getByText('Permission')).toBeTruthy()
expect(screen.getByText('Choose default permission mode')).toBeTruthy()
const selector = screen.getByRole<HTMLButtonElement>('button', { name: /Read only/ })
expect(selector.disabled).toBe(true)
it('renders the item slot as the section body', () => {
const { renderSlot } = mount()
expect(renderSlot).toHaveBeenCalledWith('settings.general.item', {})
expect(screen.getByTestId('slot-settings.general.item')).toBeTruthy()
})
})
it('renders the Tool Call skeleton cubes with schema pinned selected', () => {
mount()
describe('ToolCallSkeleton', () => {
it('renders the mode cubes with schema pinned selected', () => {
render(<ToolCallSkeleton {...kit} t={t} />)
expect(screen.getByText('Tool Call')).toBeTruthy()
const schema = screen.getByText('Schema mode')
const code = screen.getByText('Code mode')
@@ -65,10 +67,4 @@ describe('GeneralSection', () => {
expect(screen.getByText('Traditional function calling — invoke tools one at a time')).toBeTruthy()
expect(screen.getByText('Chain multiple tools with code — multi-step orchestration')).toBeTruthy()
})
it('renders the feature-contributed item slot after the skeleton rows', () => {
const { renderSlot } = mount()
expect(renderSlot).toHaveBeenCalledWith('settings.general.item', {})
expect(screen.getByTestId('slot-settings.general.item')).toBeTruthy()
})
})