The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): render plugin-declared settings in the Plugins tab (#46600, #87934)
teknium15c0e73eff1d9
diff --git a/apps/desktop/src/app/capabilities/plugins/plugin-settings-form.test.tsx b/apps/desktop/src/app/capabilities/plugins/plugin-settings-form.test.tsxnew file mode 100644index 00000000000..94efb07a394--- /dev/null+++ b/apps/desktop/src/app/capabilities/plugins/plugin-settings-form.test.tsx@@ -0,0 +1,77 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import type { PluginSettingField } from '@/store/agent-plugins'++import { collectChanges, initialDraft, PluginSettingsForm } from './plugin-settings-form'++const FIELDS: PluginSettingField[] = [+ {+ description: 'Service endpoint',+ key: 'api_url',+ label: 'API URL',+ required: true,+ type: 'string',+ value: 'https://a'+ },+ { description: '', key: 'retries', label: 'Retries', required: false, type: 'number', value: 3 },+ { description: '', key: 'verbose', label: 'Verbose', required: false, type: 'boolean', value: false },+ {+ choices: ['fast', 'careful'],+ description: '',+ key: 'mode',+ label: 'Mode',+ required: false,+ type: 'enum',+ value: 'fast'+ },+ {+ description: 'Token',+ env: 'DEMO_API_KEY',+ has_value: true,+ key: 'api_key',+ label: 'API key',+ required: false,+ type: 'secret'+ },+ { description: '', key: 'extra', label: 'Extra', required: false, type: 'json', value: { a: 1 } }+]++describe('PluginSettingsForm (#46600, #87934)', () => {+ afterEach(cleanup)++ it('renders one control per schema type from the table, secrets masked with no value echoed', () => {+ render(<PluginSettingsForm disabled={false} fields={FIELDS} idPrefix="p" onSave={vi.fn(async () => true)} />)++ expect((screen.getByLabelText('API URL') as HTMLInputElement).value).toBe('https://a')+ expect((screen.getByLabelText(/^Retries/) as HTMLInputElement).type).toBe('number')+ expect(screen.getByRole('switch', { name: 'Verbose' }).getAttribute('aria-checked')).toBe('false')+ expect(screen.getByRole('combobox', { name: 'Mode' })).toBeTruthy()+ const secret = screen.getByLabelText(/^API key/) as HTMLInputElement+ expect(secret.type).toBe('password')+ expect(secret.value).toBe('')+ expect(secret.placeholder).toContain('set')+ expect((screen.getByLabelText(/^Extra/) as HTMLTextAreaElement).value).toBe(JSON.stringify({ a: 1 }, null, 2))+ // Nothing changed yet → nothing to save.+ expect((screen.getByRole('button', { name: 'Save settings' }) as HTMLButtonElement).disabled).toBe(true)+ })++ it('submits only what changed, coerced to wire types, secrets routed by env name; clears secrets after save', async () => {+ const onSave = vi.fn(async () => true)+ render(<PluginSettingsForm disabled={false} fields={FIELDS} idPrefix="p" onSave={onSave} />)++ fireEvent.change(screen.getByLabelText(/^Retries/), { target: { value: '9' } })+ fireEvent.click(screen.getByRole('switch', { name: 'Verbose' }))+ fireEvent.change(screen.getByLabelText(/^API key/), { target: { value: 'sk-x' } })+ fireEvent.submit(screen.getByTestId('p-settings-form'))++ await vi.waitFor(() =>+ expect(onSave).toHaveBeenCalledWith({ secrets: { DEMO_API_KEY: 'sk-x' }, values: { retries: 9, verbose: true } })+ )+ await vi.waitFor(() => expect((screen.getByLabelText(/^API key/) as HTMLInputElement).value).toBe(''))++ // A value the plugin cannot accept never reaches the backend.+ expect(() => collectChanges(FIELDS, { ...initialDraft(FIELDS), mode: 'reckless' })).toThrow(/Mode/)+ expect(() => collectChanges(FIELDS, { ...initialDraft(FIELDS), retries: 'five' })).toThrow(/number/)+ })+})diff --git a/apps/desktop/src/app/capabilities/plugins/plugin-settings-form.tsx b/apps/desktop/src/app/capabilities/plugins/plugin-settings-form.tsxnew file mode 100644index 00000000000..55a4bf96b7c--- /dev/null+++ b/apps/desktop/src/app/capabilities/plugins/plugin-settings-form.tsx@@ -0,0 +1,299 @@+import { type ReactNode, useMemo, useState } from 'react'++import { Button } from '@/components/ui/button'+import { Field, FieldHint } from '@/components/ui/field'+import { Input } from '@/components/ui/input'+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'+import { Switch } from '@/components/ui/switch'+import { Textarea } from '@/components/ui/textarea'+import { useI18n } from '@/i18n'+import type { PluginSettingField, PluginSettingFieldType } from '@/store/agent-plugins'++// A plugin manifest's `config_schema` rendered as a form. Every non-secret+// value is edited as TEXT (the draft) and coerced to its wire type on save, so a+// half-typed number never fights the input; secrets are drafted separately and+// only ever sent to the `.env` credential route by the caller.++export type PluginSettingsDraft = Record<string, string>++export interface PluginSettingsSave {+ values: Record<string, unknown>+ secrets: Record<string, string>+}++interface ControlProps {+ field: PluginSettingField+ id: string+ raw: string+ disabled: boolean+ onChange: (raw: string) => void+ /** Localised hint for a secret that already has a stored value. */+ secretSetHint: string+}++/** What the input shows before the user touches it. */+const INITIAL_TEXT: Record<PluginSettingFieldType, (field: PluginSettingField) => string> = {+ boolean: field => (field.value === true ? 'true' : 'false'),+ enum: field => String(field.value ?? field.choices?.[0] ?? ''),+ json: field => (field.value === undefined || field.value === null ? '' : JSON.stringify(field.value, null, 2)),+ number: field => (field.value === undefined || field.value === null ? '' : String(field.value)),+ secret: () => '',+ string: field => String(field.value ?? '')+}++/** Text → wire value; a thrown Error is the field's validation message. */+const COERCE: Record<Exclude<PluginSettingFieldType, 'secret'>, (raw: string, field: PluginSettingField) => unknown> = {+ boolean: raw => raw === 'true',+ enum: (raw, field) => {+ if (!field.choices?.includes(raw)) {+ throw new Error(`${field.label}: not one of ${field.choices?.join(', ') ?? ''}`)+ }++ return raw+ },+ json: (raw, field) => {+ const parsed: unknown = JSON.parse(raw || 'null')++ if (parsed === null || typeof parsed !== 'object') {+ throw new Error(`${field.label}: expected a JSON list or object`)+ }++ return parsed+ },+ number: (raw, field) => {+ const n = Number(raw)++ if (raw.trim() === '' || Number.isNaN(n)) {+ throw new Error(`${field.label}: expected a number`)+ }++ return n+ },+ string: raw => raw+}++const TEXT_CLASS = 'h-7 text-xs'++function StringControl({ disabled, id, onChange, raw }: ControlProps) {+ return (+ <Input+ className={TEXT_CLASS}+ disabled={disabled}+ id={id}+ onChange={e => onChange(e.currentTarget.value)}+ value={raw}+ />+ )+}++function NumberControl({ disabled, id, onChange, raw }: ControlProps) {+ return (+ <Input+ className={TEXT_CLASS}+ disabled={disabled}+ id={id}+ inputMode="decimal"+ onChange={e => onChange(e.currentTarget.value)}+ type="number"+ value={raw}+ />+ )+}++function BooleanControl({ disabled, field, id, onChange, raw }: ControlProps) {+ return (+ <Switch+ aria-label={field.label}+ checked={raw === 'true'}+ disabled={disabled}+ id={id}+ onCheckedChange={on => onChange(on ? 'true' : 'false')}+ />+ )+}++function EnumControl({ disabled, field, id, onChange, raw }: ControlProps) {+ return (+ <Select disabled={disabled} onValueChange={onChange} value={raw}>+ <SelectTrigger aria-label={field.label} className={TEXT_CLASS} id={id}>+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ {(field.choices ?? []).map(choice => (+ <SelectItem key={choice} value={choice}>+ {choice}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ )+}++function SecretControl({ disabled, field, id, onChange, raw, secretSetHint }: ControlProps) {+ return (+ <Input+ autoComplete="off"+ className={TEXT_CLASS}+ data-env={field.env}+ disabled={disabled}+ id={id}+ onChange={e => onChange(e.currentTarget.value)}+ placeholder={field.has_value ? secretSetHint : ''}+ type="password"+ value={raw}+ />+ )+}++function JsonControl({ disabled, id, onChange, raw }: ControlProps) {+ return (+ <Textarea+ className="min-h-16 font-mono text-xs"+ disabled={disabled}+ id={id}+ onChange={e => onChange(e.currentTarget.value)}+ spellCheck={false}+ value={raw}+ />+ )+}++/** Field type → control. Adding a manifest type means one row here, one in+ * INITIAL_TEXT and one in COERCE — never a branch in the renderer. */+export const FIELD_CONTROLS: Record<PluginSettingFieldType, (props: ControlProps) => ReactNode> = {+ boolean: BooleanControl,+ enum: EnumControl,+ json: JsonControl,+ number: NumberControl,+ secret: SecretControl,+ string: StringControl+}++export function initialDraft(fields: PluginSettingField[]): PluginSettingsDraft {+ return Object.fromEntries(fields.map(field => [field.key, INITIAL_TEXT[field.type](field)]))+}++/** Split a draft into the two payloads: coerced non-secret values that+ * CHANGED, and non-blank secrets keyed by their `.env` name. Throws the first+ * field's validation error. */+export function collectChanges(fields: PluginSettingField[], draft: PluginSettingsDraft): PluginSettingsSave {+ const initial = initialDraft(fields)+ const values: Record<string, unknown> = {}+ const secrets: Record<string, string> = {}++ for (const field of fields) {+ const raw = draft[field.key] ?? ''++ if (field.type === 'secret') {+ if (raw && field.env) {+ secrets[field.env] = raw+ }++ continue+ }++ if (raw !== initial[field.key]) {+ values[field.key] = COERCE[field.type](raw, field)+ }+ }++ return { values, secrets }+}++export function PluginSettingsForm({+ fields,+ idPrefix,+ disabled,+ onSave+}: {+ fields: PluginSettingField[]+ idPrefix: string+ disabled: boolean+ /** Resolves true when everything landed; the form then re-seeds from `fields`. */+ onSave: (changes: PluginSettingsSave) => Promise<boolean>+}) {+ const { t } = useI18n()+ const s = t.skills.plugins.settingsForm+ const seed = useMemo(() => initialDraft(fields), [fields])+ const [draft, setDraft] = useState<PluginSettingsDraft>(seed)+ const [seedRef, setSeedRef] = useState(seed)+ const [error, setError] = useState<null | string>(null)++ // The row's refreshed copy re-seeds the form (a saved value becomes the new baseline).+ if (seedRef !== seed) {+ setSeedRef(seed)+ setDraft(seed)+ }++ const dirty = fields.some(field => (draft[field.key] ?? '') !== seed[field.key])++ const save = async () => {+ let changes: PluginSettingsSave++ try {+ changes = collectChanges(fields, draft)+ } catch (e) {+ setError(e instanceof Error ? e.message : String(e))++ return+ }++ setError(null)++ if (await onSave(changes)) {+ // Secrets are never echoed back; clear them so the placeholder shows "set".+ setDraft(current =>+ Object.fromEntries(fields.map(field => [field.key, field.type === 'secret' ? '' : (current[field.key] ?? '')]))+ )+ }+ }++ return (+ <form+ className="grid gap-3"+ data-testid={`${idPrefix}-settings-form`}+ onSubmit={event => {+ event.preventDefault()+ void save()+ }}+ >+ <div className="grid items-start gap-3 sm:grid-cols-2">+ {fields.map(field => {+ const id = `${idPrefix}-${field.key}`+ const Control = FIELD_CONTROLS[field.type]++ return (+ <Field+ htmlFor={id}+ key={field.key}+ label={field.label}+ optional={!field.required}+ optionalLabel={s.optional}+ >+ <Control+ disabled={disabled}+ field={field}+ id={id}+ onChange={raw => setDraft(current => ({ ...current, [field.key]: raw }))}+ raw={draft[field.key] ?? ''}+ secretSetHint={s.secretSet}+ />+ {(field.description || field.type === 'secret') && (+ <FieldHint>+ {field.description}+ {field.type === 'secret' && field.env ? ` ${s.secretStoredAs(field.env)}` : ''}+ </FieldHint>+ )}+ </Field>+ )+ })}+ </div>+ {error && <FieldHint error>{error}</FieldHint>}+ <div className="flex items-center justify-end gap-2">+ <Button disabled={disabled || !dirty} size="xs" type="submit" variant="outline">+ {s.save}+ </Button>+ </div>+ </form>+ )+}diff --git a/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx b/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsxindex 244b8f634a1..e5d34c15153 100644--- a/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx+++ b/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx@@ -9,6 +9,7 @@ import {useState} from 'react'+import { setEnvVar } from '@/api/config'import { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'import { Button } from '@/components/ui/button'import { Codicon } from '@/components/ui/codicon'@@ -33,6 +34,7 @@ import {isDesktopRelevantPlugin,loadAgentPlugins,removeAgentPlugin,+ saveAgentPluginSettings,toggleAgentPlugin,updateAgentPlugin} from '@/store/agent-plugins'@@ -48,6 +50,7 @@ import { Pill } from '../../settings/primitives'import { useDeepLinkHighlight } from '../../settings/use-deep-link-highlight'import { mergePluginPackages, type PackageKind, type PluginPackage } from './plugin-packages'+import { PluginSettingsForm } from './plugin-settings-form'// The REAL Plugin Catalog page (docs site) embedded as a one-click picker —// the same pattern as the Skills tab's EmbeddedHubPicker. `?embed=picker`@@ -222,8 +225,10 @@ function Dash() {function PackageRow({pkg,scope,+ profile,scopeLabel,busy,+ request,onAgentToggle,onAgentUpdate,onAgentRemove,@@ -231,8 +236,10 @@ function PackageRow({}: {pkg: PluginPackagescope: null | string+ profile: ProfileScopescopeLabel: stringbusy: boolean+ request: GatewayRequestonAgentToggle: (row: AgentPluginRow, enable: boolean) => voidonAgentUpdate: (row: AgentPluginRow) => voidonAgentRemove: (row: AgentPluginRow) => void@@ -243,6 +250,10 @@ function PackageRow({const d = t.settings.pluginsconst desktop = pkg.desktopconst agent = pkg.agent+ // Manifest `config_schema` → an inline settings form under the row (#46600, #87934).+ const settingsFields = agent?.settings_schema ?? []+ const hasSettings = Boolean(agent?.key) && settingsFields.length > 0+ const [settingsOpen, setSettingsOpen] = useState(false)const desktopOn = desktop ? desktop.status !== 'disabled' : falseconst agentOn = agent?.status === 'enabled'const agentToggleable = Boolean(agent?.key)@@ -259,151 +270,199 @@ function PackageRow({const remoteBackend = useStore($connection)?.mode === 'remote'return (- <div- className="flex items-center gap-3 border-b border-(--ui-stroke-tertiary) px-3 py-2.5 last:border-b-0"- data-testid={`plugin-row-${pkg.key}`}- id={pluginElementId(agent?.key ?? agent?.name ?? desktop?.id ?? pkg.key)}- role="row"- >- <div className="flex min-w-0 flex-1 items-start gap-2" role="cell">- <div className="min-w-0 flex-1">- <div className="flex flex-wrap items-center gap-2 text-[length:var(--conversation-text-font-size)] font-medium text-foreground">- <span>{pkg.name}</span>- {agent?.version && <span className="text-(--ui-text-quaternary)">v{agent.version}</span>}- <KindBadge kind={pkg.kind} />- <ProvenancePill pkg={pkg} />- {agent?.portable && <Pill>{p.portableBadge}</Pill>}- {desktop?.status === 'error' && <Pill tone="primary">{d.failed}</Pill>}- </div>- {(desktop?.status === 'error' ? desktop.error : pkg.description) && (- <div- className={cn(- 'mt-0.5 text-[length:var(--conversation-caption-font-size)] break-words',- desktop?.status === 'error' ? 'text-(--ui-danger,#f87171)' : 'text-(--ui-text-tertiary)'- )}- >- {desktop?.status === 'error' ? desktop.error : pkg.description}+ <>+ <div+ className={cn(+ 'flex items-center gap-3 border-b border-(--ui-stroke-tertiary) px-3 py-2.5',+ !settingsOpen && 'last:border-b-0'+ )}+ data-testid={`plugin-row-${pkg.key}`}+ id={pluginElementId(agent?.key ?? agent?.name ?? desktop?.id ?? pkg.key)}+ role="row"+ >+ <div className="flex min-w-0 flex-1 items-start gap-2" role="cell">+ <div className="min-w-0 flex-1">+ <div className="flex flex-wrap items-center gap-2 text-[length:var(--conversation-text-font-size)] font-medium text-foreground">+ <span>{pkg.name}</span>+ {agent?.version && <span className="text-(--ui-text-quaternary)">v{agent.version}</span>}+ <KindBadge kind={pkg.kind} />+ <ProvenancePill pkg={pkg} />+ {agent?.portable && <Pill>{p.portableBadge}</Pill>}+ {desktop?.status === 'error' && <Pill tone="primary">{d.failed}</Pill>}</div>- )}- </div>- {/* Fixed slot so the switch column stays straight whether or not+ {(desktop?.status === 'error' ? desktop.error : pkg.description) && (+ <div+ className={cn(+ 'mt-0.5 text-[length:var(--conversation-caption-font-size)] break-words',+ desktop?.status === 'error' ? 'text-(--ui-danger,#f87171)' : 'text-(--ui-text-tertiary)'+ )}+ >+ {desktop?.status === 'error' ? desktop.error : pkg.description}+ </div>+ )}+ </div>+ {/* Fixed slot so the switch column stays straight whether or notthis row has a folder to reveal (bundled plugins have none). */}- <span className="flex size-7 shrink-0 items-center justify-center">- {desktop?.file && (- <Tip label={d.reveal}>- <Button onClick={() => reveal(desktop.file!)} size="icon" variant="ghost">- <Codicon name="folder-opened" size="0.85rem" />- </Button>- </Tip>- )}- </span>- {/* Same fixed-slot treatment for Uninstall: present on every row so the+ <span className="flex size-7 shrink-0 items-center justify-center">+ {desktop?.file && (+ <Tip label={d.reveal}>+ <Button onClick={() => reveal(desktop.file!)} size="icon" variant="ghost">+ <Codicon name="folder-opened" size="0.85rem" />+ </Button>+ </Tip>+ )}+ </span>+ {/* Fixed slot for the settings gear: only plugins whose manifest declares+ a config_schema get one. */}+ <span className="flex size-7 shrink-0 items-center justify-center">+ {hasSettings && (+ <Tip label={p.settingsToggle(pkg.name)}>+ <Button+ aria-expanded={settingsOpen}+ aria-label={p.settingsToggle(pkg.name)}+ className={cn(settingsOpen && 'text-foreground')}+ onClick={() => setSettingsOpen(open => !open)}+ size="icon"+ variant="ghost"+ >+ <Codicon name="settings-gear" size="0.85rem" />+ </Button>+ </Tip>+ )}+ </span>+ {/* Same fixed-slot treatment for Uninstall: present on every row so thehalves line up, populated when the agent half is a user install orthe row is a standalone desktop plugin. */}- <span className="flex size-7 shrink-0 items-center justify-center">- {agent && agentRemovable ? (- <Tip label={p.uninstallTip(pkg.name, scopeLabel)}>- <Button- aria-label={`${p.uninstall}: ${pkg.name}`}- className="text-(--ui-text-tertiary) hover:text-(--ui-danger,#f87171)"- disabled={busy}- onClick={() => onAgentRemove(agent)}- size="icon"- variant="ghost"- >- <Trash2 className="size-3.5" />- </Button>- </Tip>- ) : desktop && desktopRemovable ? (- <Tip label={p.uninstallDesktopTip(pkg.name)}>- <Button- aria-label={`${p.uninstall}: ${pkg.name}`}- className="text-(--ui-text-tertiary) hover:text-(--ui-danger,#f87171)"- onClick={() => onDesktopRemove(desktop)}- size="icon"- variant="ghost"- >- <Trash2 className="size-3.5" />- </Button>- </Tip>- ) : null}- </span>- </div>+ <span className="flex size-7 shrink-0 items-center justify-center">+ {agent && agentRemovable ? (+ <Tip label={p.uninstallTip(pkg.name, scopeLabel)}>+ <Button+ aria-label={`${p.uninstall}: ${pkg.name}`}+ className="text-(--ui-text-tertiary) hover:text-(--ui-danger,#f87171)"+ disabled={busy}+ onClick={() => onAgentRemove(agent)}+ size="icon"+ variant="ghost"+ >+ <Trash2 className="size-3.5" />+ </Button>+ </Tip>+ ) : desktop && desktopRemovable ? (+ <Tip label={p.uninstallDesktopTip(pkg.name)}>+ <Button+ aria-label={`${p.uninstall}: ${pkg.name}`}+ className="text-(--ui-text-tertiary) hover:text-(--ui-danger,#f87171)"+ onClick={() => onDesktopRemove(desktop)}+ size="icon"+ variant="ghost"+ >+ <Trash2 className="size-3.5" />+ </Button>+ </Tip>+ ) : null}+ </span>+ </div>- {/* The two halves. Desktop is app-level and reads the same whichever+ {/* The two halves. Desktop is app-level and reads the same whicheverprofile is selected; Agent follows the selector. A half the packagelacks shows a dash; a half it has but which is missing on this sideshows the install affordance. */}- <HalfCell label={p.halfDesktop}>- {desktop ? (- <Switch- aria-label={`${p.halfDesktop}: ${pkg.name}`}- checked={desktopOn}- onCheckedChange={on => {- triggerHaptic('selection')- void setPluginEnabled(desktop.id, on)+ <HalfCell label={p.halfDesktop}>+ {desktop ? (+ <Switch+ aria-label={`${p.halfDesktop}: ${pkg.name}`}+ checked={desktopOn}+ onCheckedChange={on => {+ triggerHaptic('selection')+ void setPluginEnabled(desktop.id, on)+ }}+ />+ ) : pkg.desktopMissing ? (+ <Tip label={remoteBackend ? p.desktopHalfRemoteTip : p.desktopHalfPendingTip}>+ <span className="text-[0.65rem] text-(--ui-text-tertiary)">+ {remoteBackend ? p.desktopHalfRemote : p.desktopHalfPending}+ </span>+ </Tip>+ ) : (+ <Dash />+ )}+ </HalfCell>++ <HalfCell label={p.halfAgentIn(scopeLabel)}>+ {agent ? (+ <>+ {agent.update_available && (+ <Button+ className="h-5 px-1.5 text-[0.65rem]"+ disabled={busy}+ onClick={() => onAgentUpdate(agent)}+ size="xs"+ variant="outline"+ >+ {p.updateToPin(agent.catalog_version ?? agent.catalog_sha?.slice(0, 8) ?? '')}+ </Button>+ )}+ {busy && <Loader2 className="size-3.5 animate-spin text-(--ui-text-tertiary)" />}+ {agentToggleable ? (+ <Switch+ aria-label={`${p.halfAgent}: ${pkg.name}`}+ checked={agentOn}+ disabled={busy}+ onCheckedChange={on => onAgentToggle(agent, on)}+ />+ ) : (+ <Tip label={p.legacyBackend}>+ <span>+ <Switch aria-label={`${p.halfAgent}: ${pkg.name}`} checked={agentOn} disabled />+ </span>+ </Tip>+ )}+ </>+ ) : pkg.agentMissingInProfile && desktop ? (+ <Tip label={desktop.packageOrigin?.repo ? p.installAgentHereTip(scopeLabel) : p.installAgentHereNoOrigin}>+ <span>+ <Button+ className="h-5 px-1.5 text-[0.65rem]"+ disabled={!desktop.packageOrigin?.repo}+ onClick={() => installAgentHalfHere(desktop, scope)}+ size="xs"+ variant="outline"+ >+ {p.installAgentHere}+ </Button>+ </span>+ </Tip>+ ) : (+ <Dash />+ )}+ </HalfCell>+ </div>+ {hasSettings && settingsOpen && agent?.key && (+ <div className="border-b border-(--ui-stroke-tertiary) bg-(--ui-bg-secondary,transparent) px-3 py-3 last:border-b-0">+ <PluginSettingsForm+ disabled={busy}+ fields={settingsFields}+ idPrefix={`plugin-settings-${agent.key}`}+ onSave={async changes => {+ const ok = await saveAgentPluginSettings(request, {+ key: agent.key!,+ values: changes.values,+ secrets: changes.secrets,+ writeSecret: (env, value) => setEnvVar(env, value, profile),+ failMessage: p.settingsForm.saveFailed(pkg.name),+ profile: scope+ })++ if (ok) {+ notify({ kind: 'success', message: p.settingsForm.saved(pkg.name) })+ }++ return ok}}/>- ) : pkg.desktopMissing ? (- <Tip label={remoteBackend ? p.desktopHalfRemoteTip : p.desktopHalfPendingTip}>- <span className="text-[0.65rem] text-(--ui-text-tertiary)">- {remoteBackend ? p.desktopHalfRemote : p.desktopHalfPending}- </span>- </Tip>- ) : (- <Dash />- )}- </HalfCell>-- <HalfCell label={p.halfAgentIn(scopeLabel)}>- {agent ? (- <>- {agent.update_available && (- <Button- className="h-5 px-1.5 text-[0.65rem]"- disabled={busy}- onClick={() => onAgentUpdate(agent)}- size="xs"- variant="outline"- >- {p.updateToPin(agent.catalog_version ?? agent.catalog_sha?.slice(0, 8) ?? '')}- </Button>- )}- {busy && <Loader2 className="size-3.5 animate-spin text-(--ui-text-tertiary)" />}- {agentToggleable ? (- <Switch- aria-label={`${p.halfAgent}: ${pkg.name}`}- checked={agentOn}- disabled={busy}- onCheckedChange={on => onAgentToggle(agent, on)}- />- ) : (- <Tip label={p.legacyBackend}>- <span>- <Switch aria-label={`${p.halfAgent}: ${pkg.name}`} checked={agentOn} disabled />- </span>- </Tip>- )}- </>- ) : pkg.agentMissingInProfile && desktop ? (- <Tip label={desktop.packageOrigin?.repo ? p.installAgentHereTip(scopeLabel) : p.installAgentHereNoOrigin}>- <span>- <Button- className="h-5 px-1.5 text-[0.65rem]"- disabled={!desktop.packageOrigin?.repo}- onClick={() => installAgentHalfHere(desktop, scope)}- size="xs"- variant="outline"- >- {p.installAgentHere}- </Button>- </span>- </Tip>- ) : (- <Dash />- )}- </HalfCell>- </div>+ </div>+ )}+ </>)}@@ -687,6 +746,8 @@ export const PluginsTab = memo(function PluginsTab({})}}pkg={pkg}+ profile={profile}+ request={requestGateway}scope={scope}scopeLabel={label}/>diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex f0a2e02be94..0861d6ac13a 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -1899,7 +1899,17 @@ export const en: Translations = {deepLinkCatalogUnknown: (name: string) =>`\u201C${name}\u201D is not in the Hermes plugin catalog. Nothing was installed.`,deepLinkCatalogUnavailable:- 'Could not load the Hermes plugin catalog. Check your connection and open the link again.'+ 'Could not load the Hermes plugin catalog. Check your connection and open the link again.',+ settingsToggle: (name: string) => `Settings: ${name}`,+ settingsForm: {+ save: 'Save settings',+ saved: (name: string) => `${name} settings saved.`,+ saveFailed: (name: string) => `Could not save ${name} settings`,+ optional: '(optional)',+ secretSet: '•••••••• (set)',+ secretStoredAs: (env: string) =>+ `Stored in the profile's .env as ${env}, never in config.yaml; leave blank to keep the current value.`+ }},officialCatalog: 'Available to install',officialPill: 'Official',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 0009eaac31c..50af98e54e8 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -1619,6 +1619,15 @@ export interface Translations {deepLinkCatalogInvalidName: stringdeepLinkCatalogUnknown: (name: string) => stringdeepLinkCatalogUnavailable: string+ settingsToggle: (name: string) => string+ settingsForm: {+ save: string+ saved: (name: string) => string+ saveFailed: (name: string) => string+ optional: string+ secretSet: string+ secretStoredAs: (env: string) => string+ }}officialCatalog: stringofficialPill: stringdiff --git a/apps/desktop/src/store/agent-plugins.test.ts b/apps/desktop/src/store/agent-plugins.test.tsindex 6990368f874..71c2691d8b3 100644--- a/apps/desktop/src/store/agent-plugins.test.ts+++ b/apps/desktop/src/store/agent-plugins.test.ts@@ -1,6 +1,6 @@-import { describe, expect, it } from 'vitest'+import { describe, expect, it, vi } from 'vitest'-import { type AgentPluginRow, isDesktopRelevantPlugin } from './agent-plugins'+import { $agentPlugins, type AgentPluginRow, isDesktopRelevantPlugin, saveAgentPluginSettings } from './agent-plugins'const row = (partial: Partial<AgentPluginRow>): AgentPluginRow =>({ name: partial.key ?? 'x', status: 'enabled', ...partial }) as AgentPluginRow@@ -24,3 +24,34 @@ describe('isDesktopRelevantPlugin (#98861)', () => {expect(isDesktopRelevantPlugin(row({ key: 'my-plugin', source: 'user' }))).toBe(true)})})++describe('saveAgentPluginSettings (#46600, #87934)', () => {+ it('writes values through plugins.manage settings and secrets ONLY through the credential writer', async () => {+ $agentPlugins.set([row({ key: 'demo', source: 'user' })])+ const refreshed = row({ key: 'demo', settings_schema: [], source: 'user' })+ const request = vi.fn(async () => ({ ok: true, plugin: refreshed }))+ const writeSecret = vi.fn(async () => ({ ok: true }))++ const ok = await saveAgentPluginSettings(request as never, {+ failMessage: 'fail',+ key: 'demo',+ profile: 'workbot',+ secrets: { DEMO_API_KEY: 'sk-1', DEMO_OTHER: '' },+ values: { retries: 2 },+ writeSecret+ })++ expect(ok).toBe(true)+ expect(request).toHaveBeenCalledWith('plugins.manage', {+ action: 'settings',+ key: 'demo',+ profile: 'workbot',+ values: { retries: 2 }+ })+ // Blank secret = keep; the secret value never appears in any RPC payload.+ expect(writeSecret).toHaveBeenCalledTimes(1)+ expect(writeSecret).toHaveBeenCalledWith('DEMO_API_KEY', 'sk-1')+ expect(JSON.stringify(request.mock.calls)).not.toContain('sk-1')+ expect($agentPlugins.get()[0].settings_schema).toEqual([])+ })+})diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.tsindex 4dd77e4fc73..9454b9d49cf 100644--- a/apps/desktop/src/store/agent-plugins.ts+++ b/apps/desktop/src/store/agent-plugins.ts@@ -42,6 +42,25 @@ export interface AgentPluginRow {has_desktop_half?: boolean/** Absolute install dir on the backend (informational). */install_dir?: string+ /** Manifest `config_schema` rendered as a settings form (with current values). */+ settings_schema?: PluginSettingField[]+}++export type PluginSettingFieldType = 'boolean' | 'enum' | 'json' | 'number' | 'secret' | 'string'++/** One `config_schema` key of a plugin manifest. Secrets never carry a value:+ * `env` names the `.env` variable, `has_value` whether it is set. */+export interface PluginSettingField {+ key: string+ type: PluginSettingFieldType+ label: string+ description: string+ required: boolean+ value?: unknown+ default?: unknown+ choices?: string[]+ env?: string+ has_value?: boolean}/** A `--ref` pin is a full 40-hex commit SHA; branches and tags are refused server-side. */@@ -334,3 +353,65 @@ export async function removeAgentPlugin($agentPluginBusy.set(null)}}++export interface SaveAgentPluginSettingsOptions {+ /** Canonical plugin key (`plugins.entries.<key>`). */+ key: string+ /** Non-secret `config_schema` values, already coerced to their wire types. */+ values: Record<string, unknown>+ /** Secret fields: `.env` variable name → new value (blank = unchanged, never sent). */+ secrets: Record<string, string>+ /** Writes ONE secret through the credential route (`PUT /api/env`, profile-scoped+ * by the caller) — secrets never ride the config.yaml RPC. */+ writeSecret: (env: string, value: string) => Promise<unknown>+ failMessage: string+ profile?: string | null+}++/** Persist a plugin's manifest-declared settings: values through+ * `plugins.manage settings` (the backend writes `plugins.entries.<key>.settings`+ * with the same writer `ctx.set_config` uses), secrets through `writeSecret`.+ * Patches the row from the RPC's refreshed copy so the form re-reads what+ * landed. Returns whether everything saved. */+export async function saveAgentPluginSettings(+ request: GatewayRequest,+ opts: SaveAgentPluginSettingsOptions+): Promise<boolean> {+ $agentPluginBusy.set(opts.key)++ try {+ for (const [env, value] of Object.entries(opts.secrets)) {+ if (value) {+ await opts.writeSecret(env, value)+ }+ }++ const result =+ Object.keys(opts.values).length > 0+ ? await request<{ ok?: boolean; plugin?: AgentPluginRow | null }>(+ 'plugins.manage',+ withProfile({ action: 'settings', key: opts.key, values: opts.values }, opts.profile)+ )+ : null++ if (result && !result.ok) {+ throw new Error(opts.failMessage)+ }++ if (result?.plugin) {+ const refreshed = result.plugin++ $agentPlugins.set($agentPlugins.get().map(row => (row.key === opts.key ? { ...row, ...refreshed } : row)))+ } else {+ await loadAgentPlugins(request, opts.profile)+ }++ return true+ } catch (e) {+ notifyError(e, opts.failMessage)++ return false+ } finally {+ $agentPluginBusy.set(null)+ }+}diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 43c80c323e9..211f614dd07 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -3837,7 +3837,7 @@ export interface LegacyPluginRow {version: stringenabled: boolean}-/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only). */+/** ``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name`` (+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin that widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only); ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only). */export interface PluginsManageParams {profile?: string | nullaction?: PluginsAction@@ -3850,8 +3850,9 @@ export interface PluginsManageParams {force?: boolean | nullref?: string | nullaccept_capabilities?: boolean | null+ values?: Record<string, unknown> | null}-export type PluginsAction = 'list' | 'toggle' | 'install' | 'update' | 'remove'+export type PluginsAction = 'list' | 'toggle' | 'install' | 'update' | 'remove' | 'settings'/** ``list`` → ``plugins`` + counts; ``toggle`` → ``ok``/``unchanged``/``restart_required``/``name`` (the canonical key written)/``plugin``; ``install`` → ``hermes_cli.plugins_cmd.dashboard_install_plugin``'s ok payload; ``update`` → ``ok``/``unchanged``/``sha``, or ``ok=false`` + ``consent_required`` with the ``delta`` (``{surface: [added...]}``) / ``delta_lines`` a widened pin adds — nothing changed until the client retries with ``accept_capabilities``; ``remove`` → ``ok``/``name`` plus ``cleared_memory_provider`` when the removed plugin was the live ``memory.provider``. */export interface PluginsManageResult {plugins?: AgentPluginRow[] | null@@ -3873,6 +3874,7 @@ export interface PluginsManageResult {delta?: Record<string, string[]> | nulldelta_lines?: string[] | nullerror?: string | null+ written?: string[] | null}/** ``methods_tools._plugin_rows`` + ``plugins_cmd_catalog.catalog_row_fields`` provenance. */export interface AgentPluginRow {@@ -3892,7 +3894,22 @@ export interface AgentPluginRow {catalog_version?: string | nullupdate_available?: boolean | nullpinned_sha?: string | null+ settings_schema?: PluginSettingField[] | null}+/** One ``config_schema`` key of a plugin manifest, rendered by the Plugins hub (``hermes_cli.plugins_settings.plugin_settings_fields``). ``secret`` fields carry no value: ``env`` names the ``.env`` variable and ``has_value`` whether it is set. */+export interface PluginSettingField {+ key: string+ type: PluginSettingFieldType+ label: string+ description: string+ required: boolean+ value?: unknown | null+ default?: unknown | null+ choices?: string[] | null+ env?: string | null+ has_value?: boolean | null+}+export type PluginSettingFieldType = 'string' | 'number' | 'boolean' | 'enum' | 'secret' | 'json'/** Single question: ``question`` / ``choices`` (/ ``multi_select``); batch: ``questions``. ``answers`` rides only on a reconnect replay (locks the server already accepted). */export interface ClarifyRequestParams {session_id: stringdiff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex 3348fb02100..cec85af8cf5 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -4339,6 +4339,21 @@],"default": null,"title": "Pinned Sha"+ },+ "settings_schema": {+ "anyOf": [+ {+ "items": {+ "$ref": "#/components/schemas/PluginSettingField"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Settings Schema"}},"required": [@@ -19301,13 +19316,119 @@"title": "PingResult","type": "object"},+ "PluginSettingField": {+ "additionalProperties": false,+ "description": "One ``config_schema`` key of a plugin manifest, rendered by the Plugins hub\n(``hermes_cli.plugins_settings.plugin_settings_fields``). ``secret`` fields carry no value: ``env``\nnames the ``.env`` variable and ``has_value`` whether it is set.",+ "properties": {+ "key": {+ "title": "Key",+ "type": "string"+ },+ "type": {+ "$ref": "#/components/schemas/PluginSettingFieldType"+ },+ "label": {+ "title": "Label",+ "type": "string"+ },+ "description": {+ "title": "Description",+ "type": "string"+ },+ "required": {+ "title": "Required",+ "type": "boolean"+ },+ "value": {+ "anyOf": [+ {},+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Value"+ },+ "default": {+ "anyOf": [+ {},+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Default"+ },+ "choices": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Choices"+ },+ "env": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Env"+ },+ "has_value": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Has Value"+ }+ },+ "required": [+ "key",+ "type",+ "label",+ "description",+ "required"+ ],+ "title": "PluginSettingField",+ "type": "object"+ },+ "PluginSettingFieldType": {+ "enum": [+ "string",+ "number",+ "boolean",+ "enum",+ "secret",+ "json"+ ],+ "title": "PluginSettingFieldType",+ "type": "string"+ },"PluginsAction": {"enum": ["list","toggle","install","update",- "remove"+ "remove",+ "settings"],"title": "PluginsAction","type": "string"@@ -19337,7 +19458,7 @@},"PluginsManageParams": {"additionalProperties": false,- "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only).",+ "description": "``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``\n(+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin\nthat widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only);\n``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only).","properties": {"profile": {"anyOf": [@@ -19462,6 +19583,19 @@],"default": null,"title": "Accept Capabilities"+ },+ "values": {+ "anyOf": [+ {+ "additionalProperties": true,+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Values"}},"title": "PluginsManageParams",@@ -19715,6 +19849,21 @@],"default": null,"title": "Error"+ },+ "written": {+ "anyOf": [+ {+ "items": {+ "type": "string"+ },+ "type": "array"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Written"}},"title": "PluginsManageResult",diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 221cbc84be3..cdb658aca43 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -61,7 +61,7 @@ from hermes_cli.plugins_dispatch import ( # noqa: F401 — re-exportedfrom hermes_cli.plugins_ledger import PluginLedgerMixin, PluginRegistrationfrom hermes_cli.plugins_state import (PluginState, _locked_plugin_state, _nested_plugin_mapping, _nested_plugin_value,- _plugin_relative_segments, _plugin_settings_entry,+ _plugin_relative_segments, _plugin_settings_entry, save_plugin_setting,)@@ -280,23 +280,7 @@ class PluginContext:def set_config(self, key: str, value: Any) -> None:"""Atomically write one value in this plugin's ``settings`` subtree."""- segments = self._segments(key)- from hermes_cli import config as config_mod- if config_mod.is_managed():- raise PermissionError("Plugin settings cannot be changed in a managed install")- from hermes_cli import managed_scope- full_path = ("plugins", "entries", self.plugin_id, "settings", *segments)- dotted_path = ".".join(full_path)- if managed_scope.is_key_managed(dotted_path):- raise PermissionError(f"Plugin setting {dotted_path!r} is administrator-managed")- partial = _nested_plugin_mapping(full_path[:4], _nested_plugin_mapping(segments, value))- # The lock covers merge-read plus atomic save so sibling plugin writes (threads or- # processes) cannot race between the two steps.- with _locked_plugin_state(config_mod.get_config_path()), config_mod._CONFIG_LOCK:- # Fail closed on malformed YAML: save_config degrades parse failures to {} — safe- # for reads, destructive for read-modify-write.- config_mod.read_user_config_raw()- config_mod.save_config(partial, preserve_keys={full_path}, merge_existing=True)+ save_plugin_setting(self.plugin_id, self._segments(key), value)@cached_propertydef state(self) -> PluginState:diff --git a/hermes_cli/plugins_manifest.py b/hermes_cli/plugins_manifest.pyindex d0fadf50701..dc49fbe6cdb 100644--- a/hermes_cli/plugins_manifest.py+++ b/hermes_cli/plugins_manifest.py@@ -46,6 +46,9 @@ _CONFIG_SCHEMA_TYPES: Dict[str, tuple] = {"str": (str,), "string": (str,), "int": (int,), "integer": (int,), "float": (int, float),"number": (int, float), "bool": (bool,), "boolean": (bool,), "list": (list,), "array": (list,),"dict": (dict,), "object": (dict,),+ # ``secret`` values live in ``.env`` (see hermes_cli.plugins_settings), so a config.yaml copy is+ # only ever a stray string.+ "secret": (str,),}diff --git a/hermes_cli/plugins_settings.py b/hermes_cli/plugins_settings.pynew file mode 100644index 00000000000..d6aac25adcb--- /dev/null+++ b/hermes_cli/plugins_settings.py@@ -0,0 +1,140 @@+"""Plugin-declared settings fields for the Desktop/TUI Plugins hub (#46600, #87934).++A ``plugin.yaml`` ``config_schema`` describes the keys under ``plugins.entries.<id>.settings``.+This module turns that schema into renderable form fields (type, current value, choices) and+writes edits back through :func:`hermes_cli.plugins_state.save_plugin_setting` — the same writer+``ctx.set_config`` uses, so the CLI, the plugin and the Desktop never disagree on where a+setting lives. Secrets are declared with ``type: secret`` and never touch ``config.yaml``: the+field carries the ``.env`` name (``env:`` or ``<PLUGIN>_<KEY>``) plus a presence flag, and the+client writes the value through the existing ``PUT /api/env`` credential route.+"""++from __future__ import annotations++import logging+import re+from pathlib import Path+from typing import Any, Dict, List, Mapping, Optional++from hermes_cli.plugins_state import _plugin_relative_segments, _plugin_settings_entry, save_plugin_setting++logger = logging.getLogger(__name__)++# manifest ``type`` → wire field type the renderer keys its component table on.+_FIELD_TYPES: Dict[str, str] = {+ "str": "string", "string": "string",+ "int": "number", "integer": "number", "float": "number", "number": "number",+ "bool": "boolean", "boolean": "boolean",+ "list": "json", "array": "json", "dict": "json", "object": "json",+ "secret": "secret",+}+# wire field type → Python types a saved value must have (bool is excluded from number on purpose).+_VALUE_TYPES: Dict[str, tuple] = {+ "string": (str,), "enum": (str,), "number": (int, float), "boolean": (bool,), "json": (list, dict),+}+_ENV_NAME_CLEAN_RE = re.compile(r"[^A-Z0-9]+")+++def _manifest_config_schema(plugin_dir: Optional[Path]) -> Mapping[str, Mapping[str, Any]]:+ """``config_schema`` mapping from ``<plugin_dir>/plugin.yaml``; ``{}`` when absent or malformed+ (the loader already warned about malformed entries at load time)."""+ if plugin_dir is None:+ return {}+ manifest = Path(plugin_dir) / "plugin.yaml"+ if not manifest.is_file():+ return {}+ try:+ from utils import fast_safe_load+ data = fast_safe_load(manifest.read_text(encoding="utf-8")) or {}+ except Exception as exc: # unreadable manifest: no settings surface, never a failed list+ logger.debug("plugin settings: cannot read %s: %s", manifest, exc)+ return {}+ raw = data.get("config_schema") if isinstance(data, Mapping) else None+ if not isinstance(raw, Mapping):+ return {}+ return {str(k): v for k, v in raw.items() if isinstance(v, Mapping)}+++def secret_env_name(plugin_id: str, key: str, spec: Mapping[str, Any]) -> str:+ """``.env`` variable a ``type: secret`` field is stored under: the manifest's ``env:`` or+ ``<PLUGIN_ID>_<KEY>`` upper-snaked (``image_gen/fal`` + ``api_key`` → ``IMAGE_GEN_FAL_API_KEY``)."""+ declared = str(spec.get("env") or "").strip()+ if declared:+ return declared+ return _ENV_NAME_CLEAN_RE.sub("_", f"{plugin_id}_{key}".upper()).strip("_")+++def _field_type(spec: Mapping[str, Any]) -> str:+ if spec.get("secret") is True:+ return "secret"+ kind = _FIELD_TYPES.get(str(spec.get("type") or "str").lower(), "string")+ choices = spec.get("choices", spec.get("enum"))+ if kind == "string" and isinstance(choices, list) and choices:+ return "enum"+ return kind+++def plugin_settings_fields(plugin_id: str, plugin_dir: Optional[Path]) -> List[Dict[str, Any]]:+ """Renderable settings fields for one plugin: schema + the current value of each key.++ Secret fields never carry the value — only ``env`` (where it lives) and ``has_value``.+ """+ schema = _manifest_config_schema(plugin_dir)+ if not schema:+ return []+ from hermes_cli.config import get_env_value, load_config_readonly+ entry = _plugin_settings_entry(load_config_readonly() or {}, plugin_id) or {}+ raw_current = entry.get("settings")+ current: Mapping[str, Any] = raw_current if isinstance(raw_current, Mapping) else {}+ fields: List[Dict[str, Any]] = []+ for key, spec in schema.items():+ try:+ _plugin_relative_segments(key)+ except ValueError:+ continue # a key the plugin could never read through ctx.get_config+ kind = _field_type(spec)+ field: Dict[str, Any] = {+ "key": key, "type": kind,+ "label": str(spec.get("label") or spec.get("title") or key),+ "description": str(spec.get("description") or ""),+ "required": bool(spec.get("required")),+ }+ if kind == "secret":+ env = secret_env_name(plugin_id, key, spec)+ field.update({"env": env, "has_value": get_env_value(env) is not None})+ else:+ choices = spec.get("choices", spec.get("enum"))+ if kind == "enum":+ field["choices"] = [str(c) for c in choices]+ if "default" in spec:+ field["default"] = spec["default"]+ field["value"] = current.get(key, spec.get("default"))+ fields.append(field)+ return fields+++def save_plugin_settings(plugin_id: str, plugin_dir: Optional[Path], values: Mapping[str, Any]) -> List[str]:+ """Write ``values`` (``{key: value}``) for the plugin's schema keys; returns the keys written.++ Raises ``ValueError`` on an unknown key, a type mismatch, an enum value outside ``choices`` or a+ secret (secrets go to ``.env`` through the credential route, never ``config.yaml``);+ ``PermissionError`` propagates from the shared writer (managed installs / managed keys).+ """+ schema = _manifest_config_schema(plugin_dir)+ plan: List[tuple] = []+ for key, value in values.items():+ spec = schema.get(str(key))+ if spec is None:+ raise ValueError(f"{key!r} is not declared in the plugin's config_schema")+ kind = _field_type(spec)+ if kind == "secret":+ raise ValueError(f"{key!r} is a secret; it is stored in .env, not config.yaml")+ expected = _VALUE_TYPES[kind]+ if not isinstance(value, expected) or (isinstance(value, bool) and bool not in expected):+ raise ValueError(f"{key!r} should be {kind} (got {type(value).__name__})")+ if kind == "enum" and value not in [str(c) for c in spec.get("choices", spec.get("enum"))]:+ raise ValueError(f"{key!r} must be one of the declared choices")+ plan.append((str(key), _plugin_relative_segments(str(key)), value))+ for key, segments, value in plan:+ save_plugin_setting(plugin_id, segments, value)+ return [key for key, _segments, _value in plan]diff --git a/hermes_cli/plugins_state.py b/hermes_cli/plugins_state.pyindex 5e7c7dbb1a7..127751fedf1 100644--- a/hermes_cli/plugins_state.py+++ b/hermes_cli/plugins_state.py@@ -63,6 +63,33 @@ def _plugin_settings_entry(config: object, plugin_id: str) -> Mapping[str, Any]return entry if isinstance(entry, Mapping) else None+def save_plugin_setting(plugin_id: str, segments: tuple[str, ...], value: Any) -> None:+ """Atomically write one value under ``plugins.entries.<plugin_id>.settings``.++ THE writer for plugin settings: ``PluginContext.set_config`` (the plugin itself) and the+ Desktop/TUI ``plugins.manage settings`` action both land here so managed-install and+ administrator-managed-key refusals, the cross-process lock and the fail-closed raw read+ are enforced once. ``segments`` must already be validated by :func:`_plugin_relative_segments`.+ """+ from hermes_cli import config as config_mod+ from hermes_cli import managed_scope++ if config_mod.is_managed():+ raise PermissionError("Plugin settings cannot be changed in a managed install")+ full_path = ("plugins", "entries", plugin_id, "settings", *segments)+ dotted_path = ".".join(full_path)+ if managed_scope.is_key_managed(dotted_path):+ raise PermissionError(f"Plugin setting {dotted_path!r} is administrator-managed")+ partial = _nested_plugin_mapping(full_path[:4], _nested_plugin_mapping(segments, value))+ # The lock covers merge-read plus atomic save so sibling plugin writes (threads or+ # processes) cannot race between the two steps.+ with _locked_plugin_state(config_mod.get_config_path()), config_mod._CONFIG_LOCK:+ # Fail closed on malformed YAML: save_config degrades parse failures to {} — safe+ # for reads, destructive for read-modify-write.+ config_mod.read_user_config_raw()+ config_mod.save_config(partial, preserve_keys={full_path}, merge_existing=True)++def _plugin_data_namespace(plugin_id: str, skill_namespace: str) -> str:"""Return one Windows-safe directory component for plugin-owned data. Portable Agent Plugins alreadyreceive this exact PLUGIN_DATA path; otherwise the fixed prefix avoids Windows reserved device names anddiff --git a/tests/tui_gateway/test_plugins_manage_settings.py b/tests/tui_gateway/test_plugins_manage_settings.pynew file mode 100644index 00000000000..8a274e5e70c--- /dev/null+++ b/tests/tui_gateway/test_plugins_manage_settings.py@@ -0,0 +1,66 @@+"""Gateway ``plugins.manage`` — manifest ``config_schema`` rendered as settings fields (#46600, #87934).++Drives the real discovery + config writer against a temp HERMES_HOME: ``list`` carries each user+plugin's schema with the current values, and ``settings`` writes through the same+``plugins.entries.<id>.settings`` namespace ``ctx.get_config`` reads — never a secret into config.yaml.+"""++import pytest++from tui_gateway import server++MANIFEST = """\+name: demo-plugin+version: 1.0.0+config_schema:+ api_url: {type: str, default: "https://example.invalid", description: "Service endpoint"}+ retries: {type: int, default: 3}+ verbose: {type: bool, default: false}+ mode: {type: str, choices: [fast, careful], default: fast}+ api_key: {type: secret, description: "Token"}+"""+++def plugins_home(tmp_path, monkeypatch):+ home = tmp_path / "hermes-home"+ (home / "plugins" / "demo-plugin").mkdir(parents=True)+ (home / "plugins" / "demo-plugin" / "plugin.yaml").write_text(MANIFEST, encoding="utf-8")+ (home / "config.yaml").write_text(+ "plugins:\n entries:\n demo-plugin:\n settings:\n retries: 7\n", encoding="utf-8")+ monkeypatch.setenv("HERMES_HOME", str(home))+ return home+++def _manage(**params):+ return server.handle_request({"id": "1", "method": "plugins.manage", "params": params})+++def test_list_carries_schema_fields_with_current_values_and_no_secret_values(plugins_home, monkeypatch):+ monkeypatch.setenv("DEMO_PLUGIN_API_KEY", "shh")++ rows = _manage(action="list")["result"]["plugins"]+ row = next(r for r in rows if r["key"] == "demo-plugin")+ fields = {f["key"]: f for f in row["settings_schema"]}++ assert fields["api_url"]["type"] == "string" and fields["api_url"]["value"] == "https://example.invalid"+ assert fields["retries"]["type"] == "number" and fields["retries"]["value"] == 7 # config.yaml wins over default+ assert fields["verbose"]["type"] == "boolean" and fields["verbose"]["value"] is False+ assert fields["mode"]["type"] == "enum" and fields["mode"]["choices"] == ["fast", "careful"]+ assert fields["api_key"] == {"key": "api_key", "type": "secret", "label": "api_key", "description": "Token",+ "required": False, "env": "DEMO_PLUGIN_API_KEY", "has_value": True}+++def test_settings_writes_the_plugin_namespace_and_refuses_secrets_and_bad_types(plugins_home):+ resp = _manage(action="settings", key="demo-plugin", values={"api_url": "https://real.invalid", "retries": 2, "mode": "careful"})++ assert resp["result"]["ok"] is True and sorted(resp["result"]["written"]) == ["api_url", "mode", "retries"]+ from hermes_cli.config import load_config_readonly+ assert load_config_readonly()["plugins"]["entries"]["demo-plugin"]["settings"] == {+ "api_url": "https://real.invalid", "retries": 2, "mode": "careful"}+ refreshed = {f["key"]: f["value"] for f in resp["result"]["plugin"]["settings_schema"] if "value" in f}+ assert refreshed["retries"] == 2 and refreshed["mode"] == "careful"++ for values in ({"api_key": "leak"}, {"retries": "two"}, {"mode": "reckless"}, {"unknown": 1}):+ assert _manage(action="settings", key="demo-plugin", values=values)["error"]["code"] == 4021+ assert "api_key" not in (plugins_home / "config.yaml").read_text(encoding="utf-8")diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex b87d8807348..10d8de2dcbf 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -574,12 +574,14 @@ class PluginsAction(WireEnum):install = "install"update = "update"remove = "remove"+ settings = "settings"class PluginsManageParams(ProfileParams):"""``toggle``: ``key``/``name`` + ``enable``; ``install``: ``identifier``/``repo`` or ``catalog_name``(+ ``force``, ``enable``, ``ref``); ``update``: ``name`` (+ ``accept_capabilities`` to apply a re-pin- that widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only)."""+ that widened the plugin after the user confirmed the ``delta``); ``remove``: ``name`` (user installs only);+ ``settings``: ``key`` + ``values`` (``{setting_key: value}``, non-secret schema keys only)."""action: PluginsAction = PluginsAction.listkey: str | None = None@@ -591,6 +593,33 @@ class PluginsManageParams(ProfileParams):force: bool | None = Noneref: str | None = Noneaccept_capabilities: bool | None = None+ values: dict[str, JsonValue] | None = None+++class PluginSettingFieldType(WireEnum):+ string = "string"+ number = "number"+ boolean = "boolean"+ enum = "enum"+ secret = "secret"+ json = "json"+++class PluginSettingField(Result):+ """One ``config_schema`` key of a plugin manifest, rendered by the Plugins hub+ (``hermes_cli.plugins_settings.plugin_settings_fields``). ``secret`` fields carry no value: ``env``+ names the ``.env`` variable and ``has_value`` whether it is set."""++ key: str+ type: PluginSettingFieldType+ label: str+ description: str+ required: bool+ value: JsonValue | None = None+ default: JsonValue | None = None+ choices: list[str] | None = None+ env: str | None = None+ has_value: bool | None = Noneclass AgentPluginRow(Result):@@ -612,6 +641,7 @@ class AgentPluginRow(Result):catalog_version: str | None = Noneupdate_available: bool | None = Nonepinned_sha: str | None = None+ settings_schema: list[PluginSettingField] | None = Noneclass PluginsManageResult(Result):@@ -641,6 +671,7 @@ class PluginsManageResult(Result):delta: dict[str, list[str]] | None = Nonedelta_lines: list[str] | None = Noneerror: str | None = None+ written: list[str] | None = Nonemethod("plugins.manage", params=PluginsManageParams, result=PluginsManageResult,diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex d222fbf771d..d34754d41dc 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -1460,6 +1460,8 @@ def _plugin_rows() -> list[dict]:"source": source, "status": status, "portable": pc._is_portable_plugin_dir(_dir),"install_dir": str(_dir_path) if _dir_path else "","has_desktop_half": bool(_dir_path and (_dir_path / "desktop" / "plugin.js").is_file()),+ # Manifest ``config_schema`` + current values: the Plugins hub renders these as a form.+ "settings_schema": _tools_mod("hermes_cli.plugins_settings").plugin_settings_fields(key, _dir_path),**cat.catalog_row_fields(_dir, pins, versions),**({"pinned_sha": sha} if (sha := pc.pinned_revision(name, ref_pins)) else {})})return out@@ -1535,8 +1537,29 @@ def _plugins_remove(rid, params):return _ok(rid, result) if result.get("ok") else _err(rid, 5026, result.get("error") or "remove failed")+def _plugins_settings(rid, params):+ """Write manifest-declared settings (``values`` = ``{key: value}``) through the same writer as+ ``ctx.set_config``; secrets are refused here (the client stores them via the ``.env`` route)."""+ key = (params.get("key") or params.get("name") or "").strip()+ values = params.get("values")+ if not key or not isinstance(values, dict):+ return _err(rid, 4019, "plugins.settings requires a 'key' and a 'values' mapping")+ pc = _tools_mod("hermes_cli.plugins_cmd")+ found = next((p for p in pc._discover_all_plugins() if key in (p[5], p[0])), None)+ if found is None:+ return _err(rid, 4020, f"plugin '{key}' not found")+ _name, _version, _desc, _source, plugin_dir, canonical = found+ try:+ written = _tools_mod("hermes_cli.plugins_settings").save_plugin_settings(+ canonical, Path(str(plugin_dir)) if plugin_dir else None, values)+ except (ValueError, PermissionError) as e:+ return _err(rid, 4021, str(e))+ row = next((r for r in _plugin_rows() if r["key"] == canonical), None)+ return _ok(rid, {"ok": True, "name": canonical, "written": written, "plugin": row})++_PLUGINS_ACTIONS = {"list": _plugins_list, "toggle": _plugins_toggle, "install": _plugins_install,- "update": _plugins_update, "remove": _plugins_remove}+ "update": _plugins_update, "remove": _plugins_remove, "settings": _plugins_settings}@_scoped_rpc("plugins.manage", 5026, catch_resolve=False)@@ -1545,7 +1568,7 @@ def _(rid, params: dict) -> dict:``list`` → {plugins, user_count, bundled_count}; ``toggle`` flips ``key``/``name`` per ``enable``;``install`` git-clones ``identifier``/``repo`` or a curated ``catalog_name`` (``force``, ``enable``default True); ``update`` re-pins a catalog install to the current catalog SHA; ``remove`` deletes- a user install by ``name``."""+ a user install by ``name``; ``settings`` writes manifest-declared ``values`` for ``key``."""return _run_action(rid, params, _PLUGINS_ACTIONS, "plugins")diff --git a/website/docs/developer-guide/plugins/index.md b/website/docs/developer-guide/plugins/index.mdindex 7d859c173b9..874e0666e59 100644--- a/website/docs/developer-guide/plugins/index.md+++ b/website/docs/developer-guide/plugins/index.md@@ -302,7 +302,7 @@ this Hermes understands still loads with a warning.| `requires_plugins` | list | Inter-plugin dependencies: `- id: other-plugin` with optional `version_range: ">=1.0,<2"`. **Advisory**: a missing dependency logs a clear warning but the plugin still loads — probe at runtime with `ctx.has_plugin("other-plugin")`. Load **order** honors these edges: when A requires B, B's `register()` runs before A's (topological sort, alphabetical tiebreak; cycles warn and fall back to alphabetical order). || `python_dependencies` | list of str | PEP 508 requirements (e.g. `"requests>=2.0,<3"`). Installed into Hermes' venv on `hermes plugins install` / `enable` and **re-applied after every `hermes update`** (see [Python dependencies](#python-dependencies)). A `pyproject.toml` beside `plugin.yaml` with `[project].dependencies` is the equivalent, preferred form. || `python_runtime` | str | `external` — the plugin manages its own interpreter/venv (sidecar pattern); Hermes installs nothing and leaves any `pyproject.toml` alone. |-| `config_schema` | mapping | JSON-schema-ish description of keys under `plugins.entries.<id>.settings`: `api_url: {type: str, default: "", description: "...", required: false}`. Validated at load; mismatches log actionable warnings naming the key and expected type — never load failures. Types: `str`, `int`, `float`, `bool`, `list`, `dict` (plus JSON-schema aliases). |+| `config_schema` | mapping | JSON-schema-ish description of keys under `plugins.entries.<id>.settings`: `api_url: {type: str, default: "", description: "...", required: false}`. Validated at load; mismatches log actionable warnings naming the key and expected type — never load failures. Types: `str`, `int`, `float`, `bool`, `list`, `dict` (plus JSON-schema aliases) and `secret`. Also drives the settings form in the Desktop Plugins tab — see [Settings form in the Desktop](#settings-form-in-the-desktop). || `license` | str | SPDX-style license id (e.g. `MIT`). || `homepage` | str | Project URL. || `tags` | list of str | Free-form discovery tags (e.g. `[gateway, telegram]`). |@@ -621,6 +621,41 @@ Config and state have different owners: settings are user-visible behavior in`config.yaml`, while state is plugin-owned runtime data under`<HERMES_HOME>/plugin-data/`. Neither API exposes another plugin's namespace.+### Settings form in the Desktop++Every key you declare in the manifest's `config_schema` renders as a field in the+Desktop app's **Capabilities → Plugins** tab (the gear on the plugin's row). No+Desktop code is needed: the backend's `plugins.manage list` returns the schema+plus each key's current value, and saving writes through the same writer as+`ctx.set_config()`, so `plugins.entries.<id>.settings.<key>` is what your plugin+reads back. The form is table-driven by `type`:++| Manifest `type` | Field | Extra keys |+|---|---|---|+| `str` (default) | text input | `choices: [a, b]` (or `enum:`) turns it into a dropdown |+| `int`, `float` | number input | |+| `bool` | switch | |+| `list`, `dict` | JSON editor | |+| `secret` | masked input | `env: MY_PLUGIN_TOKEN` — the `.env` variable it is stored under (default `<PLUGIN_ID>_<KEY>` upper-snaked) |++Every entry also accepts `label` (shown instead of the key), `description`+(help text under the field), `default` and `required`.++```yaml+config_schema:+ api_url: {type: str, default: "https://api.example.com", label: "API URL", description: "Service endpoint"}+ retries: {type: int, default: 3}+ mode: {type: str, choices: [fast, careful], default: fast}+ api_key: {type: secret, env: MY_PLUGIN_API_KEY, description: "Personal access token"}+```++**Secrets never touch `config.yaml`.** A `secret` field carries only the `.env`+name and whether a value is set; the Desktop stores the value through the same+credential route as provider API keys (`PUT /api/env`), and your plugin reads it+with `os.environ.get("MY_PLUGIN_API_KEY")` — exactly like a `requires_env` entry.+The `plugins.manage settings` action refuses secret keys and any value whose type+or `choices` disagree with the schema.+## Step 6: Test itStart Hermes: