Skip to content

The agent that grows with you

fix(desktop): plugin settings pages keep their profile and identity

Tekniumd8b44813b120
diff --git a/apps/desktop/src/app/capabilities/plugins/plugins-tab.test.tsx b/apps/desktop/src/app/capabilities/plugins/plugins-tab.test.tsx
index f6ef4ba9819..56d414921ee 100644
--- a/apps/desktop/src/app/capabilities/plugins/plugins-tab.test.tsx
+++ b/apps/desktop/src/app/capabilities/plugins/plugins-tab.test.tsx
@@ -739,7 +739,7 @@ describe('PluginsTab catalog UX', () => {
render(<PluginsTab profile={null} />)
fireEvent.click(screen.getByRole('button', { name: 'Settings: notes' }))
- expect(window.location.hash).toBe('#/settings?tab=plugins&plugin=agent%3Anotes')
+ expect(window.location.hash).toBe('#/settings?tab=plugins&agent=notes')
expect(screen.queryByTestId('plugin-settings-notes-settings-form')).toBeNull()
})
diff --git a/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx b/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx
index 00e7d561111..0f6d1d7ae93 100644
--- a/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx
+++ b/apps/desktop/src/app/capabilities/plugins/plugins-tab.tsx
@@ -18,7 +18,7 @@ import { Tip } from '@/components/ui/tooltip'
import { $pluginRecords, type PluginRecord, setPluginEnabled } from '@/contrib/plugins-store'
import { useContributions } from '@/contrib/react/use-contributions'
import { discoverRuntimePlugins, uninstallDiskPlugin } from '@/contrib/runtime-loader'
-import { pluginSettingsHref, SETTINGS_PLUGINS_AREA } from '@/contrib/settings-pages'
+import { pluginSettingsRouteHref, SETTINGS_PLUGINS_AREA } from '@/contrib/settings-pages'
import type { ProfileScope } from '@/hermes'
import { useI18n } from '@/i18n'
import { DESKTOP_PLUGIN_TOOLSETS } from '@/lib/desktop-toolsets'
@@ -274,8 +274,12 @@ function PackageRow({
const openSettings = () => {
// A desktop page absorbs the package's schema form as a sub-page, so its
- // plugin id is the one entry that covers both halves.
- window.location.hash = `#${pluginSettingsHref(desktopSettings ? desktop!.id : `agent:${agent!.key}`)}`
+ // plugin id is the one entry that covers both halves. The link carries
+ // the profile THIS page has selected: Settings keeps its own scope, and
+ // without the hand-off the page would open (and save) that one instead.
+ const route = desktopSettings ? { plugin: desktop!.id } : { agent: agent!.key! }
+
+ window.location.hash = `#${pluginSettingsRouteHref(route, scope)}`
}
const [desktopBusy, setDesktopBusy] = useState(false)
diff --git a/apps/desktop/src/app/settings/index.tsx b/apps/desktop/src/app/settings/index.tsx
index 11424a0e72c..f550dae314b 100644
--- a/apps/desktop/src/app/settings/index.tsx
+++ b/apps/desktop/src/app/settings/index.tsx
@@ -565,6 +565,7 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set
entries={plugins.entries}
missing={plugins.missing}
onOpen={plugins.open}
+ pending={plugins.pending}
target={plugins.target}
/>
) : activeView === 'vault' ? (
diff --git a/apps/desktop/src/app/settings/plugin-settings-ownership.test.tsx b/apps/desktop/src/app/settings/plugin-settings-ownership.test.tsx
new file mode 100644
index 00000000000..ba578047a9f
--- /dev/null
+++ b/apps/desktop/src/app/settings/plugin-settings-ownership.test.tsx
@@ -0,0 +1,308 @@
+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
+import { MemoryRouter, useLocation } from 'react-router'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import { createPluginContext } from '@/contrib/plugin'
+import { $pluginRecords, dropPlugin, publishPlugin } from '@/contrib/plugins-store'
+import { pluginSettingsHref } from '@/contrib/settings-pages'
+import { $agentPlugins, $agentPluginsStatus, type AgentPluginRow } from '@/store/agent-plugins'
+import { $activeGatewayProfile, $profiles } from '@/store/profile'
+import { $settingsScopeOverride } from '@/store/settings-scope'
+import type { ProfileInfo } from '@/types/hermes'
+
+import { PluginsTab } from '../capabilities/plugins/plugins-tab'
+import { OverlayNav } from '../overlays/overlay-split-layout'
+
+import { pluginSettingsNavChildren, PluginSettingsPane, usePluginSettingsRoute } from './plugin-settings'
+
+// Review regressions for Settings ▸ Plugins (PR #133182): every scenario here
+// reproduced natively against a real backend. Each test drives the REAL route
+// hook under a router, so the URL contract is exercised, not a local stand-in.
+
+const setEnvVar = vi.fn(async (..._args: unknown[]) => ({ ok: true }))
+
+vi.mock('@/api/config', async importOriginal => ({
+ ...(await importOriginal<object>()),
+ setEnvVar: (...args: unknown[]) => setEnvVar(...args)
+}))
+
+vi.mock('@/store/profile', async importOriginal => ({
+ ...(await importOriginal<object>()),
+ refreshProfiles: async () => []
+}))
+
+const row = (destination: string): AgentPluginRow => ({
+ description: '',
+ key: 'review-notes',
+ name: 'review-notes',
+ settings_schema: [
+ { description: '', key: 'destination', label: 'Destination', required: false, type: 'string', value: destination },
+ {
+ description: '',
+ env: 'REVIEW_TOKEN',
+ has_value: false,
+ key: 'token',
+ label: 'Token',
+ required: false,
+ type: 'secret'
+ }
+ ],
+ source: 'user',
+ status: 'enabled',
+ version: '1.0.0'
+})
+
+type Deferred = { promise: Promise<unknown>; resolve: (value: unknown) => void }
+
+const deferred = (): Deferred => {
+ let resolve!: (value: unknown) => void
+ const promise = new Promise(r => (resolve = r))
+
+ return { promise, resolve }
+}
+
+// Per-profile plugin lists the fake backend serves; a profile listed in
+// `held` answers only when the test releases it.
+let lists: Record<string, AgentPluginRow[]> = {}
+let held: Record<string, Deferred> = {}
+
+const requestGateway = vi.fn(async (method: string, params?: Record<string, unknown>): Promise<unknown> => {
+ const profile = String(params?.profile ?? 'default')
+
+ if (method === 'plugins.manage' && params?.action === 'list') {
+ if (held[profile]) {
+ await held[profile].promise
+ }
+
+ return { plugins: lists[profile] ?? [] }
+ }
+
+ if (method === 'plugins.manage' && params?.action === 'settings') {
+ return { ok: true, plugin: null }
+ }
+
+ return {}
+})
+
+vi.mock('@/app/gateway/hooks/use-gateway-request', () => ({
+ useGatewayRequest: () => ({ requestGateway })
+}))
+
+const profile = (name: string, isDefault = false): ProfileInfo => ({ is_default: isDefault, name }) as ProfileInfo
+
+const Icon = () => null
+
+let currentLocation = ''
+
+function SettingsPlugins() {
+ const route = usePluginSettingsRoute(true)
+ const location = useLocation()
+
+ currentLocation = `${location.pathname}${location.search}`
+
+ return (
+ <>
+ <OverlayNav
+ groups={[
+ {
+ active: true,
+ children: pluginSettingsNavChildren(route.entries, route.target, route.open),
+ icon: Icon,
+ id: 'plugins',
+ label: 'Plugins',
+ onSelect: () => route.open(null)
+ }
+ ]}
+ />
+ <PluginSettingsPane {...route} onOpen={route.open} />
+ </>
+ )
+}
+
+const renderSettings = (path: string) =>
+ render(
+ <MemoryRouter initialEntries={[path]}>
+ <SettingsPlugins />
+ </MemoryRouter>
+ )
+
+const chip = (name: string) =>
+ screen.queryAllByRole('button', { name }).find(el => el.className.includes('rounded-full'))
+
+const settingsCalls = () =>
+ requestGateway.mock.calls.filter(([method, params]) => method === 'plugins.manage' && params?.action === 'settings')
+
+/** Click a Capabilities ▸ Plugins gear and return the deep link it produced. */
+function gearHref(props: Parameters<typeof PluginsTab>[0], label: string): string {
+ window.location.hash = ''
+ const view = render(<PluginsTab {...props} />)
+
+ fireEvent.click(screen.getByRole('button', { name: label }))
+ view.unmount()
+
+ return window.location.hash.slice(1)
+}
+
+describe('Settings ▸ Plugins ownership (review of #133182)', () => {
+ const disposers: Array<() => void> = []
+
+ beforeEach(() => {
+ lists = { default: [row('DEFAULT-ready')], 'review-b': [row('B-original')], 'review-empty': [] }
+ held = {}
+ requestGateway.mockClear()
+ setEnvVar.mockClear()
+ $agentPlugins.set([])
+ $agentPluginsStatus.set('idle')
+ $activeGatewayProfile.set('default')
+ $settingsScopeOverride.set(null)
+ $profiles.set([profile('default', true), profile('review-b'), profile('review-empty')])
+ })
+
+ afterEach(() => {
+ cleanup()
+ disposers.splice(0).forEach(dispose => dispose())
+ $settingsScopeOverride.set(null)
+ window.location.hash = ''
+ })
+
+ // P1: a dirty draft (secret included) must never be submitted to the profile
+ // the user switched to while that profile's list was still loading.
+ it('drops the old profile’s draft on a profile switch and never saves it into the new profile', async () => {
+ renderSettings(pluginSettingsHref())
+ await waitFor(() => expect(document.querySelector('[data-tour$="review-notes"]')).toBeTruthy())
+ fireEvent.click(document.querySelector<HTMLButtonElement>('[data-tour$="review-notes"]')!)
+
+ const destination = await screen.findByLabelText(/Destination/)
+
+ expect((destination as HTMLInputElement).value).toBe('DEFAULT-ready')
+ fireEvent.change(destination, { target: { value: 'DEFAULT-UNSAVED' } })
+ fireEvent.change(screen.getByLabelText('Token'), { target: { value: 'DEFAULT-SECRET' } })
+
+ held['review-b'] = deferred()
+ fireEvent.click(chip('review-b')!)
+
+ // B's list is still in flight: the A draft must be gone, and nothing can be saved.
+ const stale = screen.queryByLabelText(/Destination/) as HTMLInputElement | null
+
+ expect(stale?.value ?? '').not.toBe('DEFAULT-UNSAVED')
+ expect((screen.queryByLabelText('Token') as HTMLInputElement | null)?.value ?? '').toBe('')
+
+ const save = screen.queryByRole('button', { name: 'Save settings' }) as HTMLButtonElement | null
+
+ if (save && !save.disabled) {
+ fireEvent.click(save)
+ }
+
+ await act(async () => {
+ held['review-b']!.resolve(undefined)
+ await held['review-b']!.promise
+ })
+
+ await waitFor(() => expect((screen.getByLabelText(/Destination/) as HTMLInputElement).value).toBe('B-original'))
+ expect(settingsCalls()).toEqual([])
+ expect(setEnvVar).not.toHaveBeenCalled()
+
+ // Saving now writes B's own edit to B.
+ fireEvent.change(screen.getByLabelText(/Destination/), { target: { value: 'B-EDIT' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Save settings' }))
+ await waitFor(() => expect(settingsCalls()).toHaveLength(1))
+ expect(settingsCalls()[0]![1]).toMatchObject({ profile: 'review-b', values: { destination: 'B-EDIT' } })
+ })
+
+ // P1: the Capabilities gear carries the profile Capabilities had selected,
+ // and Settings opens (and saves) THAT profile — not its own scope.
+ it('opens the gear’s page for the profile selected in Capabilities', async () => {
+ $agentPlugins.set(lists['review-b']!)
+ $agentPluginsStatus.set('ready')
+
+ const href = gearHref({ profile: 'review-b' }, 'Settings: review-notes')
+
+ expect(new URLSearchParams(href.split('?')[1]).get('profile')).toBe('review-b')
+
+ $agentPlugins.set([])
+ $agentPluginsStatus.set('idle')
+ requestGateway.mockClear()
+ renderSettings(href)
+
+ await waitFor(() => expect((screen.getByLabelText(/Destination/) as HTMLInputElement).value).toBe('B-original'))
+ expect($settingsScopeOverride.get()).toBe('review-b')
+ // The one-shot hand-off is consumed: the URL no longer pins the scope.
+ expect(new URLSearchParams(currentLocation.split('?')[1]).get('profile')).toBeNull()
+
+ fireEvent.change(screen.getByLabelText(/Destination/), { target: { value: 'GEAR-FOR-B' } })
+ fireEvent.click(screen.getByRole('button', { name: 'Save settings' }))
+ await waitFor(() => expect(settingsCalls()).toHaveLength(1))
+ expect(settingsCalls()[0]![1]).toMatchObject({ profile: 'review-b', values: { destination: 'GEAR-FOR-B' } })
+ })
+
+ // P2: a profile without the plugin must keep the "Applies to" selector so the
+ // user can switch back.
+ it('keeps the profile selector on the overview when the selected profile lacks the plugin', async () => {
+ renderSettings(pluginSettingsHref())
+ await waitFor(() => expect(document.querySelector('[data-tour$="review-notes"]')).toBeTruthy())
+ fireEvent.click(document.querySelector<HTMLButtonElement>('[data-tour$="review-notes"]')!)
+ await screen.findByLabelText(/Destination/)
+
+ fireEvent.click(chip('review-empty')!)
+ await waitFor(() => expect(screen.queryByLabelText(/Destination/)).toBeNull())
+ await waitFor(() => expect(screen.getByText('No plugin has settings yet.')).toBeTruthy())
+
+ expect(chip('default')).toBeTruthy()
+ fireEvent.click(chip('default')!)
+ await waitFor(() => expect(document.querySelector('[data-tour$="review-notes"]')).toBeTruthy())
+ })
+
+ // P2: desktop plugin `agent` registering page `notes` must not share an
+ // identity with agent plugin `notes`'s automatic page.
+ it('keeps a desktop page and an agent page apart even when their ids line up', async () => {
+ lists.default = [{ ...row('AGENT-NOTES'), key: 'notes', name: 'notes' }]
+ publishPlugin(
+ { id: 'agent', kind: 'disk', name: 'Adversarial', status: 'loaded' },
+ {
+ activate: () => undefined,
+ deactivate: () => undefined
+ }
+ )
+ disposers.push(() => dropPlugin('agent'))
+ createPluginContext('agent', dispose => disposers.push(dispose)).registerSettingsPage({
+ id: 'notes',
+ render: () => <p>Desktop landing</p>,
+ title: 'Desktop notes'
+ })
+
+ renderSettings(pluginSettingsHref())
+ await waitFor(() => expect(screen.getAllByRole('button', { name: /notes/ }).length).toBeGreaterThan(1))
+
+ const ids = [...document.querySelectorAll('[data-tour^="nav-plugins:"]')].map(el => el.getAttribute('data-tour'))
+
+ expect(new Set(ids).size).toBe(ids.length)
+
+ // The agent row's gear opens the agent form, not the desktop page.
+ $agentPlugins.set(lists.default)
+ $agentPluginsStatus.set('ready')
+ expect($pluginRecords.get().agent).toBeTruthy()
+
+ const href = gearHref({ profile: 'default' }, 'Settings: notes')
+
+ cleanup()
+ renderSettings(href)
+ await waitFor(() => expect((screen.getByLabelText(/Destination/) as HTMLInputElement).value).toBe('AGENT-NOTES'))
+ expect(screen.queryByText('Desktop landing')).toBeNull()
+ })
+
+ // P2: `config` is an ordinary sub-page id; the automatic schema form must not
+ // consume it.
+ it('keeps a plugin sub-page named config reachable by rail and by deep link', async () => {
+ createPluginContext('weather', dispose => disposers.push(dispose)).registerSettingsPage({
+ children: [{ id: 'config', render: () => <p>CONFIG CHILD CONTENT</p>, title: 'Configuration child' }],
+ id: 'main',
+ render: () => <p>Weather home</p>,
+ title: 'Weather'
+ })
+
+ renderSettings(pluginSettingsHref('weather', 'config'))
+ await waitFor(() => expect(screen.getByText('CONFIG CHILD CONTENT')).toBeTruthy())
+ expect(screen.queryByText('Weather home')).toBeNull()
+ expect(screen.getByRole('button', { name: 'Configuration child' })).toBeTruthy()
+ })
+})
diff --git a/apps/desktop/src/app/settings/plugin-settings.test.tsx b/apps/desktop/src/app/settings/plugin-settings.test.tsx
index adcf5dbff87..43b33351663 100644
--- a/apps/desktop/src/app/settings/plugin-settings.test.tsx
+++ b/apps/desktop/src/app/settings/plugin-settings.test.tsx
@@ -3,7 +3,7 @@ import { useState } from 'react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { createPluginContext } from '@/contrib/plugin'
-import { resolvePluginSettingsTarget } from '@/contrib/settings-pages'
+import { type PluginSettingsRoute, resolvePluginSettingsTarget } from '@/contrib/settings-pages'
import { $agentPlugins, $agentPluginsStatus, type AgentPluginRow } from '@/store/agent-plugins'
import { OverlayNav } from '../overlays/overlay-split-layout'
@@ -40,12 +40,9 @@ const Icon = () => null
function Harness() {
const entries = usePluginSettingsEntries()
- const [selection, setSelection] = useState<{ page: null | string; plugin: null | string }>({
- page: null,
- plugin: null
- })
- const target = resolvePluginSettingsTarget(entries, selection.plugin, selection.page)
- const open = (plugin: null | string, page?: string) => setSelection({ page: page ?? null, plugin })
+ const [route, setRoute] = useState<null | PluginSettingsRoute>(null)
+ const target = resolvePluginSettingsTarget(entries, route)
+ const open = setRoute
return (
<>
@@ -99,15 +96,15 @@ describe('Settings ▸ Plugins', () => {
// The automatic config_schema page arrives with the agent plugin list.
await waitFor(() => expect(railItem('plugins:agent:notes')).toBeTruthy())
- expect(railItem('plugins:weather:main')?.textContent).toBe('Weather')
+ expect(railItem('plugins:desktop:weather:main')?.textContent).toBe('Weather')
// Sub-pages stay folded until their plugin is selected.
- expect(railItem('plugins:weather:main:units')).toBeNull()
+ expect(railItem('plugins:desktop:weather:main:units')).toBeNull()
- fireEvent.click(railItem('plugins:weather:main')!)
+ fireEvent.click(railItem('plugins:desktop:weather:main')!)
expect(screen.getByText('Weather home')).toBeTruthy()
- expect(railItem('plugins:weather:main:alerts')?.textContent).toBe('Alerts')
+ expect(railItem('plugins:desktop:weather:main:alerts')?.textContent).toBe('Alerts')
- fireEvent.click(railItem('plugins:weather:main:units')!)
+ fireEvent.click(railItem('plugins:desktop:weather:main:units')!)
expect(screen.getByText('Units content')).toBeTruthy()
expect(screen.queryByText('Weather home')).toBeNull()
})
@@ -145,11 +142,11 @@ describe('Settings ▸ Plugins', () => {
ctx.registerSettingsPage({ id: 'main', render: () => <p>Weather home</p>, title: 'Weather' })
render(<Harness />)
- expect(railItem('plugins:weather:main')).toBeTruthy()
+ expect(railItem('plugins:desktop:weather:main')).toBeTruthy()
// Disable = the loader runs every tracked disposer.
disposers.splice(0).forEach(dispose => dispose())
- await waitFor(() => expect(railItem('plugins:weather:main')).toBeNull())
+ await waitFor(() => expect(railItem('plugins:desktop:weather:main')).toBeNull())
})
it('shows an overview with an empty state when no plugin has settings', async () => {
diff --git a/apps/desktop/src/app/settings/plugin-settings.tsx b/apps/desktop/src/app/settings/plugin-settings.tsx
index 71d833589d0..052c125b54a 100644
--- a/apps/desktop/src/app/settings/plugin-settings.tsx
+++ b/apps/desktop/src/app/settings/plugin-settings.tsx
@@ -10,8 +10,14 @@ import { $pluginRecords } from '@/contrib/plugins-store'
import { ContribBoundary, ContribRender } from '@/contrib/react/boundary'
import { useContributions } from '@/contrib/react/use-contributions'
import {
+ PLUGIN_SETTINGS_PROFILE_PARAM,
pluginSettingsEntries,
type PluginSettingsEntry,
+ pluginSettingsNavId,
+ type PluginSettingsNode,
+ type PluginSettingsRoute,
+ pluginSettingsRouteFrom,
+ pluginSettingsRouteOf,
type PluginSettingsTarget,
resolvePluginSettingsTarget,
SETTINGS_PLUGINS_AREA
@@ -21,13 +27,14 @@ import type { IconComponent } from '@/lib/icons'
import {
$agentPluginBusy,
$agentPlugins,
+ $agentPluginsProfile,
$agentPluginsStatus,
isDesktopRelevantPlugin,
loadAgentPlugins,
saveAgentPluginSettings
} from '@/store/agent-plugins'
-import { notify } from '@/store/notifications'
-import { $settingsRequestProfile } from '@/store/settings-scope'
+import { notify, notifyError } from '@/store/notifications'
+import { $settingsRequestProfile, setSettingsScope } from '@/store/settings-scope'
import { desktopPackageName } from '../capabilities/plugins/plugin-packages'
import type { OverlayNavLink } from '../overlays/overlay-split-layout'
@@ -37,9 +44,8 @@ import { PluginSettingsForm } from './plugin-settings-form'
import { EmptyState, ListRowSkeleton, SectionHeading, SettingsContent } from './primitives'
import { SettingsProfileScope } from './profile-scope'
-/** Opens Settings ▸ Plugins at an entry (by key) and optional sub-page;
- * `null` = the overview. */
-export type OpenPluginSettings = (plugin: null | string, page?: string) => void
+/** Opens Settings ▸ Plugins at a route; `null` = the overview. */
+export type OpenPluginSettings = (route: null | PluginSettingsRoute) => void
const MANAGE_PLUGINS_HREF = `#${CAPABILITIES_ROUTE}?tab=plugins`
@@ -74,47 +80,87 @@ export const PAGE_SCOPED_PARAMS = [
'label',
'origin',
'plugin',
- 'ppage'
+ 'ppage',
+ 'agent',
+ PLUGIN_SETTINGS_PROFILE_PARAM
] as const
-/** Settings ▸ Plugins routing: `?tab=plugins&plugin=<entry key | plugin id |
- * agent:<key>>&ppage=<sub-page>`. `active` = the Plugins view is showing. */
+/** The profile the Settings plugin pages edit, as `plugins.manage` and the
+ * agent-plugin store key it (`null` = the backend's launch profile). */
+const ownerKey = (scope: string | undefined): null | string => scope ?? null
+
+/** The agent plugin rows loaded for `owner`, or none while the shared list
+ * still holds another profile's rows (a switch in flight, or Capabilities
+ * loaded a different profile). */
+function useOwnedAgentPlugins(owner: null | string) {
+ const rows = useStore($agentPlugins)
+ const loadedFor = useStore($agentPluginsProfile)
+ const status = useStore($agentPluginsStatus)
+ const owned = loadedFor === owner
+
+ return { owned, rows: owned ? rows : [], settled: status === 'error' || (status === 'ready' && owned), status }
+}
+
+/** Settings ▸ Plugins routing: `?tab=plugins&plugin=<entry key | plugin id>
+ * &ppage=<sub-page>` for desktop pages, `?tab=plugins&agent=<key>` for an
+ * agent plugin's schema form. A `&profile=` hand-off (the Capabilities gear)
+ * is adopted into the Settings scope, then dropped from the URL. `active` =
+ * the Plugins view is showing. */
export function usePluginSettingsRoute(active: boolean) {
const navigate = useNavigate()
const { hash, pathname, search } = useLocation()
const entries = usePluginSettingsEntries()
- const status = useStore($agentPluginsStatus)
+ const { settled } = useOwnedAgentPlugins(ownerKey(useStore($settingsRequestProfile)))
const params = new URLSearchParams(search)
- const requested = params.get('plugin')
- const target = active ? resolvePluginSettingsTarget(entries, requested, params.get('ppage')) : null
- // A deep link to an agent plugin's page can't resolve until the list loads;
- // only call it missing once the load has settled.
- const settled = status !== 'idle' && status !== 'loading'
+ const route = pluginSettingsRouteFrom(params)
+ const handoff = active ? params.get(PLUGIN_SETTINGS_PROFILE_PARAM) : null
+ // Until the hand-off is adopted, the current scope is not the one the link
+ // asked for: resolve nothing, so no page renders against the wrong profile.
+ const target = active && !handoff ? resolvePluginSettingsTarget(entries, route) : null
+
+ useEffect(() => {
+ if (!handoff) {
+ return
+ }
+
+ setSettingsScope(handoff)
+
+ const next = new URLSearchParams(search)
+
+ next.delete(PLUGIN_SETTINGS_PROFILE_PARAM)
+ navigate({ hash, pathname, search: `?${next}` }, { replace: true })
+ }, [handoff, hash, navigate, pathname, search])
const open = useCallback<OpenPluginSettings>(
- (plugin, page) => {
- const next = new URLSearchParams(search)
+ next => {
+ const query = new URLSearchParams(search)
for (const key of PAGE_SCOPED_PARAMS) {
- next.delete(key)
+ query.delete(key)
}
- next.set('tab', 'plugins')
+ query.set('tab', 'plugins')
- if (plugin) {
- next.set('plugin', plugin)
- }
+ if (next && 'agent' in next) {
+ query.set('agent', next.agent)
+ } else if (next) {
+ query.set('plugin', next.plugin)
- if (plugin && page) {
- next.set('ppage', page)
+ if (next.page) {
+ query.set('ppage', next.page)
+ }
}
- navigate({ hash, pathname, search: `?${next}` }, { replace: true })
+ navigate({ hash, pathname, search: `?${query}` }, { replace: true })
},
[hash, navigate, pathname, search]
)
- return { entries, missing: Boolean(requested) && !target && settled, open, target }
+ // A deep link to an agent plugin's page can't resolve until the scope's
+ // list loads; only call it missing once that load has settled.
+ const waiting = Boolean(route) && !target && (Boolean(handoff) || !settled)
+
+ return { entries, missing: Boolean(route) && !target && !waiting, open, pending: active && waiting, target }
}
/** Every plugin settings page, live: Desktop plugins' registered pages plus an
@@ -124,14 +170,22 @@ export function usePluginSettingsEntries(): PluginSettingsEntry[] {
const { t } = useI18n()
const { requestGateway } = useGatewayRequest()
const contributions = useContributions(SETTINGS_PLUGINS_AREA)
- const rows = useStore($agentPlugins)
const records = useStore($pluginRecords)
- const scope = useStore($settingsRequestProfile)
+ const owner = ownerKey(useStore($settingsRequestProfile))
+ const { owned, rows, status } = useOwnedAgentPlugins(owner)
// Cheap backend disk scan; the same loader Capabilities ▸ Plugins uses.
useEffect(() => {
- void loadAgentPlugins(requestGateway, scope ?? null)
- }, [requestGateway, scope])
+ void loadAgentPlugins(requestGateway, owner)
+ }, [requestGateway, owner])
+
+ // The list is shared: if another surface replaced it with a different
+ // profile's rows, fetch this scope's again rather than show none.
+ useEffect(() => {
+ if (status === 'ready' && !owned) {
+ void loadAgentPlugins(requestGateway, owner)
+ }
+ }, [owned, owner, requestGateway, status])
const configTitle = t.settings.pluginPages.agentSettings
@@ -151,6 +205,12 @@ export function usePluginSettingsEntries(): PluginSettingsEntry[] {
)
}
+const isActiveNode = (target: null | PluginSettingsTarget, entry: PluginSettingsEntry, child: PluginSettingsNode) =>
+ target?.entry.uid === entry.uid &&
+ (child.agentKey
+ ? target.child?.agentKey === child.agentKey
+ : !target.child?.agentKey && target.child?.id === child.id)
+
/** The Settings rail's children under "Plugins": one row per entry, its
* sub-pages folded beneath it while it is selected. */
export function pluginSettingsNavChildren(
@@ -159,21 +219,21 @@ export function pluginSettingsNavChildren(
open: OpenPluginSettings
): OverlayNavLink[] {
return entries.map(entry => {
- const active = target?.entry.key === entry.key
+ const active = target?.entry.uid === entry.uid
return {
active,
children: entry.children.map(child => ({
- active: active && target?.child?.id === child.id,
+ active: isActiveNode(target, entry, child),
icon: iconFor(child.agentKey ? 'settings-gear' : 'list-flat'),
- id: `plugins:${entry.key}:${child.id}`,
+ id: pluginSettingsNavId(entry, child),
label: child.title,
- onSelect: () => open(entry.key, child.id)
+ onSelect: () => open(pluginSettingsRouteOf(entry, child))
})),
icon: entryIcon(entry),
- id: `plugins:${entry.key}`,
+ id: pluginSettingsNavId(entry),
label: entry.title,
- onSelect: () => open(entry.key)
+ onSelect: () => open(pluginSettingsRouteOf(entry))
}
})
}
@@ -196,6 +256,9 @@ function PluginSettingsOverview({
return (
<SettingsContent>
+ {/* The agent half of this list is per profile: keep the selector here
+ too, or a profile without the plugin strands the user (no way back). */}
+ <SettingsProfileScope className="mb-5" />
<SectionHeading
aside={
// Page-level action on the heading row, like Passwords & Logins' Add.
@@ -212,7 +275,10 @@ function PluginSettingsOverview({
/>
<p className={BLURB_CLASS}>{copy.blurb}</p>
{missing && (
- <p className="mb-2 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-secondary)" role="status">
+ <p
+ className="mb-2 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-secondary)"
+ role="status"
+ >
{copy.missing}
</p>
)}
@@ -228,9 +294,9 @@ function PluginSettingsOverview({
return (
<button
className="flex min-h-11 items-center gap-3 border-b border-(--ui-stroke-tertiary) px-3 text-left transition-colors last:border-b-0 hover:bg-(--chrome-action-hover)"
- data-testid={`plugin-settings-row-${entry.key}`}
- key={entry.key}
- onClick={() => onOpen(entry.key)}
+ data-testid={`plugin-settings-row-${entry.uid}`}
+ key={entry.uid}
+ onClick={() => onOpen(pluginSettingsRouteOf(entry))}
type="button"
>
<Icon className="size-4 shrink-0 text-(--ui-text-tertiary)" />
@@ -252,51 +318,73 @@ function PluginSettingsOverview({
)
}
+function PluginSettingsLoading() {
+ return (
+ <SettingsContent>
+ <SettingsProfileScope className="mb-5" />
+ <div className="grid gap-1">
+ <ListRowSkeleton />
+ <ListRowSkeleton />
+ <ListRowSkeleton />
+ </div>
+ </SettingsContent>
+ )
+}
+
/** Automatic page for an agent plugin's manifest `config_schema`: the schema
- * form, saved through `plugins.manage settings` (+ `.env` for secrets) for
- * the profile the Settings scope selector targets. */
-function PluginSchemaSettingsPage({ agentKey }: { agentKey: string }) {
+ * form, saved through `plugins.manage settings` (+ `.env` for secrets).
+ *
+ * Bound to ONE profile for its whole life: the pane keys it by
+ * (profile, plugin) so a scope switch remounts it (the draft goes with the
+ * old profile), it renders only rows loaded for that profile, and its save
+ * writes that profile or nothing. */
+function PluginSchemaSettingsPage({ agentKey, owner }: { agentKey: string; owner: null | string }) {
const { t } = useI18n()
const p = t.skills.plugins
const { requestGateway } = useGatewayRequest()
- const row = useStore($agentPlugins).find(candidate => candidate.key === agentKey)
+ const { rows } = useOwnedAgentPlugins(owner)
+ const row = rows.find(candidate => candidate.key === agentKey)
const busy = useStore($agentPluginBusy) === agentKey
- const scope = useStore($settingsRequestProfile)
+
+ if (!row?.settings_schema?.length) {
+ return <PluginSettingsLoading />
+ }
return (
<SettingsContent>
<SettingsProfileScope className="mb-5" />
- {row?.settings_schema?.length ? (
- <PluginSettingsForm
- disabled={busy}
- fields={row.settings_schema}
- idPrefix={`plugin-settings-${agentKey}`}
- intro={row.description ? <p className={BLURB_CLASS}>{row.description}</p> : undefined}
- onSave={async changes => {
- const ok = await saveAgentPluginSettings(requestGateway, {
- failMessage: p.settingsForm.saveFailed(row.name),
- key: agentKey,
- profile: scope ?? null,
- secrets: changes.secrets,
- values: changes.values,
- writeSecret: (env, value) => setEnvVar(env, value, scope)
- })
-
- if (ok) {
- notify({ kind: 'success', message: p.settingsForm.saved(row.name) })
- }
-
- return ok
- }}
- title={row.name}
- />
- ) : (
- <div className="grid gap-1">
- <ListRowSkeleton />
- <ListRowSkeleton />
- <ListRowSkeleton />
- </div>
- )}
+ <PluginSettingsForm
+ disabled={busy}
+ fields={row.settings_schema}
+ idPrefix={`plugin-settings-${agentKey}`}
+ intro={row.description ? <p className={BLURB_CLASS}>{row.description}</p> : undefined}
+ onSave={async changes => {
+ // Belt and braces: the key remount already discards a draft when
+ // the scope moves, but a submit must never write a profile other
+ // than the one these values were loaded from.
+ if (ownerKey($settingsRequestProfile.get()) !== owner || $agentPluginsProfile.get() !== owner) {
+ notifyError(null, p.settingsForm.saveFailed(row.name))
+
+ return false
+ }
+
+ const ok = await saveAgentPluginSettings(requestGateway, {
+ failMessage: p.settingsForm.saveFailed(row.name),
+ key: agentKey,
+ profile: owner,
+ secrets: changes.secrets,
+ values: changes.values,
+ writeSecret: (env, value) => setEnvVar(env, value, owner ?? undefined)
+ })
+
+ if (ok) {
+ notify({ kind: 'success', message: p.settingsForm.saved(row.name) })
+ }
+
+ return ok
+ }}
+ title={row.name}
+ />
</SettingsContent>
)
}
@@ -308,22 +396,35 @@ export function PluginSettingsPane({
entries,
missing = false,
onOpen,
+ pending = false,
target
}: {
entries: readonly PluginSettingsEntry[]
- /** A `?plugin=` was requested but matches no page (disabled/uninstalled). */
+ /** A page was requested but matches none (disabled/uninstalled). */
missing?: boolean
onOpen: OpenPluginSettings
+ /** A page was requested and the scope's plugin list is still loading. */
+ pending?: boolean
target: null | PluginSettingsTarget
}) {
+ const owner = ownerKey(useStore($settingsRequestProfile))
+
if (!target) {
- return <PluginSettingsOverview entries={entries} missing={missing} onOpen={onOpen} />
+ return pending ? (
+ <PluginSettingsLoading />
+ ) : (
+ <PluginSettingsOverview entries={entries} missing={missing} onOpen={onOpen} />
+ )
}
const node = target.child ?? target.entry
if (node.agentKey) {
- return <PluginSchemaSettingsPage agentKey={node.agentKey} key={node.agentKey} />
+ // Keyed by (profile, plugin): a scope switch remounts the form, so a
+ // draft never outlives the profile it was typed against.
+ return (
+ <PluginSchemaSettingsPage agentKey={node.agentKey} key={JSON.stringify([owner, node.agentKey])} owner={owner} />
+ )
}
const render = node.render
@@ -335,7 +436,7 @@ export function PluginSettingsPane({
// Keyed per page so a sub-page switch remounts the plugin's tree (fresh
// hook state, fresh error boundary) instead of reconciling across pages.
return (
- <SettingsContent key={`${target.entry.key}:${target.child?.id ?? ''}`}>
+ <SettingsContent key={JSON.stringify([target.entry.uid, target.child?.id ?? null])}>
<ContribBoundary id={target.entry.key}>
<ContribRender render={render} />
</ContribBoundary>
diff --git a/apps/desktop/src/contrib/settings-pages.test.ts b/apps/desktop/src/contrib/settings-pages.test.ts
index f8181f3ec2f..3cbe59677ed 100644
--- a/apps/desktop/src/contrib/settings-pages.test.ts
+++ b/apps/desktop/src/contrib/settings-pages.test.ts
@@ -7,6 +7,9 @@ import { registry } from './registry'
import {
pluginSettingsEntries,
pluginSettingsHref,
+ pluginSettingsNavId,
+ pluginSettingsRouteFrom,
+ pluginSettingsRouteHref,
resolvePluginSettingsTarget,
SETTINGS_PLUGINS_AREA
} from './settings-pages'
@@ -114,7 +117,14 @@ describe('pluginSettingsEntries', () => {
})
expect(entries).toHaveLength(1)
- expect(entries[0]).toMatchObject({ agentKey: 'notes', children: [], key: 'agent:notes', title: 'notes' })
+ expect(entries[0]).toMatchObject({
+ agentKey: 'notes',
+ children: [],
+ key: 'notes',
+ kind: 'agent',
+ title: 'notes',
+ uid: 'agent:notes'
+ })
})
it('folds a unified package’s schema form into its desktop page as a sub-page', () => {
@@ -126,7 +136,47 @@ describe('pluginSettingsEntries', () => {
})
expect(entries).toHaveLength(1)
- expect(entries[0]?.children).toEqual([{ agentKey: 'pixel_overlay', id: 'config', title: 'Agent settings' }])
+ expect(entries[0]?.children).toEqual([{ agentKey: 'pixel_overlay', id: 'pixel_overlay', title: 'Agent settings' }])
+ })
+
+ // Review of #133182: a desktop plugin may pick ANY id, so `agent` + page
+ // `notes` once produced the same `agent:notes` key as agent plugin `notes`.
+ it('keeps desktop pages and automatic agent pages in disjoint identity namespaces', () => {
+ const entries = pluginSettingsEntries({
+ configTitle: 'Agent settings',
+ contributions: [page('agent:notes', 'Desktop notes')],
+ rows: [row({ key: 'notes', name: 'notes', settings_schema: [field] })]
+ })
+
+ expect(entries.map(entry => entry.uid).sort()).toEqual(['agent:notes', 'desktop:agent:notes'])
+ expect(new Set(entries.map(entry => pluginSettingsNavId(entry))).size).toBe(2)
+ expect(resolvePluginSettingsTarget(entries, { agent: 'notes' })?.entry.kind).toBe('agent')
+ expect(resolvePluginSettingsTarget(entries, { plugin: 'agent:notes' })?.entry.kind).toBe('desktop')
+ expect(resolvePluginSettingsTarget(entries, { plugin: 'agent' })?.entry.kind).toBe('desktop')
+ })
+
+ // Review of #133182: `config` was silently reserved for the folded schema form.
+ it('never consumes a plugin-chosen sub-page id for the folded schema form', () => {
+ const entries = pluginSettingsEntries({
+ configTitle: 'Agent settings',
+ contributions: [
+ page('pixel-overlay:main', 'Pixel Overlay', {
+ data: { children: [{ id: 'config', render, title: 'Configuration child' }] }
+ })
+ ],
+ packageOf: pluginId => (pluginId === 'pixel-overlay' ? 'config' : null),
+ rows: [row({ key: 'config', name: 'config', settings_schema: [field] })]
+ })
+
+ expect(entries[0]?.children.map(child => child.title)).toEqual(['Configuration child', 'Agent settings'])
+ expect(resolvePluginSettingsTarget(entries, { page: 'config', plugin: 'pixel-overlay' })?.child?.title).toBe(
+ 'Configuration child'
+ )
+ expect(resolvePluginSettingsTarget(entries, { agent: 'config' })?.child?.title).toBe('Agent settings')
+
+ const [child, schema] = entries[0]!.children
+
+ expect(pluginSettingsNavId(entries[0]!, child)).not.toBe(pluginSettingsNavId(entries[0]!, schema))
})
})
@@ -141,30 +191,48 @@ describe('resolvePluginSettingsTarget', () => {
]
})
- it('finds an entry by its key or by the plugin id, and a sub-page under it', () => {
- expect(resolvePluginSettingsTarget(entries, 'weather:main', null)?.entry.title).toBe('Weather')
- expect(resolvePluginSettingsTarget(entries, 'weather', 'units')?.child?.title).toBe('Units')
- expect(resolvePluginSettingsTarget(entries, 'weather', 'nope')?.child).toBeUndefined()
+ it('finds a desktop entry by its key or by the plugin id, and a sub-page under it', () => {
+ expect(resolvePluginSettingsTarget(entries, { plugin: 'weather:main' })?.entry.title).toBe('Weather')
+ expect(resolvePluginSettingsTarget(entries, { page: 'units', plugin: 'weather' })?.child?.title).toBe('Units')
+ expect(resolvePluginSettingsTarget(entries, { page: 'nope', plugin: 'weather' })?.child).toBeUndefined()
})
- it('routes an agent:<key> deep link to the folded sub-page or the standalone page', () => {
- const folded = resolvePluginSettingsTarget(entries, 'agent:weather_pkg', null)
+ it('routes an agent key to the folded sub-page or the standalone page', () => {
+ const folded = resolvePluginSettingsTarget(entries, { agent: 'weather_pkg' })
expect(folded?.entry.key).toBe('weather:main')
expect(folded?.child?.agentKey).toBe('weather_pkg')
- expect(resolvePluginSettingsTarget(entries, 'agent:notes', null)?.entry.agentKey).toBe('notes')
+ expect(resolvePluginSettingsTarget(entries, { agent: 'notes' })?.entry.agentKey).toBe('notes')
+ // An agent key is never matched as a desktop plugin id, nor vice versa.
+ expect(resolvePluginSettingsTarget(entries, { plugin: 'notes' })).toBeNull()
+ expect(resolvePluginSettingsTarget(entries, { agent: 'weather' })).toBeNull()
})
it('returns null for an unknown plugin (overview fallback)', () => {
- expect(resolvePluginSettingsTarget(entries, 'gone', null)).toBeNull()
- expect(resolvePluginSettingsTarget(entries, null, null)).toBeNull()
+ expect(resolvePluginSettingsTarget(entries, { plugin: 'gone' })).toBeNull()
+ expect(resolvePluginSettingsTarget(entries, null)).toBeNull()
})
})
describe('pluginSettingsHref', () => {
it('builds the Settings ▸ Plugins deep link', () => {
expect(pluginSettingsHref()).toBe('/settings?tab=plugins')
- expect(pluginSettingsHref('agent:image_gen/fal')).toBe('/settings?tab=plugins&plugin=agent%3Aimage_gen%2Ffal')
+ expect(pluginSettingsHref('weather')).toBe('/settings?tab=plugins&plugin=weather')
expect(pluginSettingsHref('weather', 'units')).toBe('/settings?tab=plugins&plugin=weather&ppage=units')
})
+
+ it('round-trips agent routes and the profile hand-off', () => {
+ const href = pluginSettingsRouteHref({ agent: 'image_gen/fal' }, 'review-b')
+
+ expect(href).toBe('/settings?tab=plugins&agent=image_gen%2Ffal&profile=review-b')
+
+ const params = new URLSearchParams(href.split('?')[1])
+
+ expect(pluginSettingsRouteFrom(params)).toEqual({ agent: 'image_gen/fal' })
+ expect(pluginSettingsRouteFrom(new URLSearchParams('plugin=weather&ppage=units'))).toEqual({
+ page: 'units',
+ plugin: 'weather'
+ })
+ expect(pluginSettingsRouteFrom(new URLSearchParams('tab=plugins'))).toBeNull()
+ })
})
diff --git a/apps/desktop/src/contrib/settings-pages.ts b/apps/desktop/src/contrib/settings-pages.ts
index 1f39995900a..8f8b6166407 100644
--- a/apps/desktop/src/contrib/settings-pages.ts
+++ b/apps/desktop/src/contrib/settings-pages.ts
@@ -12,6 +12,12 @@
* unified package that does both shows ONE entry; the schema form becomes
* its "Agent settings" sub-page.
*
+ * The two feeds live in disjoint identity namespaces. A desktop plugin picks
+ * any id it likes, so no string an agent key can form is safe to share with
+ * `<pluginId>:<pageId>`: entries carry their `kind`, routes carry it as the
+ * query param (`?plugin=` vs `?agent=`), and the automatic schema form is
+ * addressed by its agent key, never by a sub-page id a plugin could also pick.
+ *
* Pure: no React, no stores. The Settings view feeds it the live registry
* area and the agent plugin list.
*/
@@ -26,11 +32,9 @@ import type { Contribution } from './types'
* proposed in #91935, so a plugin written against that draft registers here. */
export const SETTINGS_PLUGINS_AREA = 'settings.plugins'
-/** Entry-key prefix for automatic config_schema pages (`agent:<key>`). */
-export const AGENT_SETTINGS_PREFIX = 'agent:'
-
-/** Sub-page id the schema form takes when folded under a desktop page. */
-export const AGENT_SETTINGS_SUBPAGE = 'config'
+/** One-shot hand-off: the profile a deep link (the Capabilities gear) wants
+ * Settings to edit. Settings adopts it into its scope and drops the param. */
+export const PLUGIN_SETTINGS_PROFILE_PARAM = 'profile'
export interface PluginSettingsSubpage {
/** Unique within the page; becomes the `ppage` URL param. */
@@ -56,6 +60,8 @@ export interface PluginSettingsPage {
}
export interface PluginSettingsNode {
+ /** Plugin-chosen sub-page id (`ppage`). Schema-form nodes are addressed by
+ * `agentKey` instead, so they never take an id a plugin could choose. */
id: string
title: string
/** Plugin-rendered content. Absent on schema-form nodes. */
@@ -64,9 +70,16 @@ export interface PluginSettingsNode {
agentKey?: string
}
+/** Which feed produced an entry; part of its identity. */
+export type PluginSettingsEntryKind = 'agent' | 'desktop'
+
export interface PluginSettingsEntry extends PluginSettingsNode {
- /** URL key: the contribution id (`<pluginId>:<pageId>`) or `agent:<key>`. */
+ kind: PluginSettingsEntryKind
+ /** Route value within `kind`: the contribution id (`<pluginId>:<pageId>`)
+ * for desktop pages, the agent plugin key for automatic pages. */
key: string
+ /** Collision-free identity across both kinds: `<kind>:<key>`. */
+ uid: string
icon?: string
order: number
/** Registering desktop plugin id, when contributed by one. */
@@ -79,6 +92,47 @@ export interface PluginSettingsTarget {
child?: PluginSettingsNode
}
+/** Where Settings ▸ Plugins should land: a desktop entry (by contribution id
+ * or plugin id, optionally a sub-page) or an agent plugin's schema form
+ * (standalone or folded under its package's desktop page). */
+export type PluginSettingsRoute = { agent: string } | { page?: string; plugin: string }
+
+/** The route that reaches `child` (or the entry's landing page). */
+export function pluginSettingsRouteOf(entry: PluginSettingsEntry, child?: PluginSettingsNode): PluginSettingsRoute {
+ if (child?.agentKey) {
+ return { agent: child.agentKey }
+ }
+
+ if (entry.kind === 'agent') {
+ return { agent: entry.key }
+ }
+
+ return child ? { page: child.id, plugin: entry.key } : { plugin: entry.key }
+}
+
+/** Read the route from Settings' query string (`null` = the overview). */
+export function pluginSettingsRouteFrom(params: URLSearchParams): null | PluginSettingsRoute {
+ const agent = params.get('agent')
+
+ if (agent) {
+ return { agent }
+ }
+
+ const plugin = params.get('plugin')
+
+ return plugin ? { page: params.get('ppage') ?? undefined, plugin } : null
+}
+
+/** Rail identity of a node: disjoint across kinds, and a folded schema form
+ * keeps the identity its standalone page would have had. */
+export function pluginSettingsNavId(entry: PluginSettingsEntry, child?: PluginSettingsNode): string {
+ if (child?.agentKey) {
+ return `plugins:agent:${child.agentKey}`
+ }
+
+ return child ? `plugins:${entry.uid}:${child.id}` : `plugins:${entry.uid}`
+}
+
/** Shape a registration into a registry contribution (the plugin context
* namespaces the id and stamps the source). */
export function settingsPageContribution(page: PluginSettingsPage): Omit<Contribution, 'source'> {
@@ -109,7 +163,7 @@ function subpagesOf(data: unknown): PluginSettingsNode[] {
continue
}
- if (seen.has(child.id) || child.id === AGENT_SETTINGS_SUBPAGE) {
+ if (seen.has(child.id)) {
continue
}
@@ -155,10 +209,12 @@ export function pluginSettingsEntries({
icon,
id: contribution.id,
key: contribution.id,
+ kind: 'desktop',
order: typeof contribution.order === 'number' ? contribution.order : 0,
pluginId: pluginIdOf(contribution.source),
render: contribution.render,
- title: contribution.title
+ title: contribution.title,
+ uid: `desktop:${contribution.id}`
})
}
@@ -179,7 +235,7 @@ export function pluginSettingsEntries({
if (owner) {
if (!owner.children.some(child => child.agentKey)) {
- owner.children.push({ agentKey: row.key, id: AGENT_SETTINGS_SUBPAGE, title: configTitle })
+ owner.children.push({ agentKey: row.key, id: row.key, title: configTitle })
}
continue
@@ -188,66 +244,87 @@ export function pluginSettingsEntries({
entries.push({
agentKey: row.key,
children: [],
- id: `${AGENT_SETTINGS_PREFIX}${row.key}`,
- key: `${AGENT_SETTINGS_PREFIX}${row.key}`,
+ id: row.key,
+ key: row.key,
+ kind: 'agent',
order: 0,
- title: row.name || row.key
+ title: row.name || row.key,
+ uid: `agent:${row.key}`
})
}
return entries.sort((a, b) => a.order - b.order || a.title.localeCompare(b.title))
}
-/** Resolve `?plugin=&ppage=` to an entry (+ sub-page). `plugin` may be the
- * entry key, the registering plugin id, or `agent:<key>` (the Capabilities
- * gear) — which also finds a schema form folded under a desktop page.
- * Null = show the overview. */
+/** Resolve a route to an entry (+ sub-page). `plugin` matches desktop
+ * entries only (by contribution id, then plugin id) and `page` only their
+ * plugin-chosen sub-pages; `agent` matches the agent key's schema form,
+ * standalone or folded under a desktop page. Null = show the overview. */
export function resolvePluginSettingsTarget(
entries: readonly PluginSettingsEntry[],
- plugin: null | string,
- page: null | string
+ route: null | PluginSettingsRoute
): null | PluginSettingsTarget {
- if (!plugin) {
+ if (!route) {
return null
}
- const pick = (entry: PluginSettingsEntry): PluginSettingsTarget => ({
- child: page ? entry.children.find(child => child.id === page) : undefined,
- entry
- })
-
- const direct = entries.find(entry => entry.key === plugin) ?? entries.find(entry => entry.pluginId === plugin)
+ if ('agent' in route) {
+ const standalone = entries.find(entry => entry.kind === 'agent' && entry.key === route.agent)
- if (direct) {
- return pick(direct)
- }
-
- if (plugin.startsWith(AGENT_SETTINGS_PREFIX)) {
- const agentKey = plugin.slice(AGENT_SETTINGS_PREFIX.length)
+ if (standalone) {
+ return { entry: standalone }
+ }
for (const entry of entries) {
- const child = entry.children.find(node => node.agentKey === agentKey)
+ const child = entry.kind === 'desktop' ? entry.children.find(node => node.agentKey === route.agent) : undefined
if (child) {
return { child, entry }
}
}
+
+ return null
}
- return null
+ const desktop = entries.filter(entry => entry.kind === 'desktop')
+
+ const entry =
+ desktop.find(candidate => candidate.key === route.plugin) ??
+ desktop.find(candidate => candidate.pluginId === route.plugin)
+
+ if (!entry) {
+ return null
+ }
+
+ return {
+ child: route.page ? entry.children.find(child => !child.agentKey && child.id === route.page) : undefined,
+ entry
+ }
}
-/** Hash-route path to Settings ▸ Plugins (▸ entry (▸ sub-page)). */
-export function pluginSettingsHref(plugin?: string, page?: string): string {
+/** Settings ▸ Plugins href for a route, optionally handing Settings the
+ * profile to edit (`PLUGIN_SETTINGS_PROFILE_PARAM`). */
+export function pluginSettingsRouteHref(route: null | PluginSettingsRoute, profile?: null | string): string {
const params = new URLSearchParams({ tab: 'plugins' })
- if (plugin) {
- params.set('plugin', plugin)
+ if (route && 'agent' in route) {
+ params.set('agent', route.agent)
+ } else if (route) {
+ params.set('plugin', route.plugin)
+
+ if (route.page) {
+ params.set('ppage', route.page)
+ }
}
- if (plugin && page) {
- params.set('ppage', page)
+ if (profile) {
+ params.set(PLUGIN_SETTINGS_PROFILE_PARAM, profile)
}
return `/settings?${params}`
}
+
+/** Hash-route path to Settings ▸ Plugins (▸ entry (▸ sub-page)). */
+export function pluginSettingsHref(plugin?: string, page?: string): string {
+ return pluginSettingsRouteHref(plugin ? { page, plugin } : null)
+}
diff --git a/apps/desktop/src/store/agent-plugins.ts b/apps/desktop/src/store/agent-plugins.ts
index 37fff96255f..d043a5dd516 100644
--- a/apps/desktop/src/store/agent-plugins.ts
+++ b/apps/desktop/src/store/agent-plugins.ts
@@ -98,6 +98,11 @@ export type GatewayRequest = <T>(method: string, params?: Record<string, unknown
export const $agentPlugins = atom<AgentPluginRow[]>([])
export const $agentPluginsStatus = atom<AgentPluginsStatus>('idle')
export const $agentPluginsError = atom<string | null>(null)
+/** The profile `$agentPlugins` was loaded for (`null` = the backend's launch
+ * profile; `undefined` = nothing loaded yet). Surfaces that write a row's
+ * settings must check it: the list is shared, and a scope switch keeps the
+ * previous profile's rows on screen until the new list lands. */
+export const $agentPluginsProfile = atom<null | string | undefined>(undefined)
/** Best available address of the row whose toggle RPC is in flight. */
export const $agentPluginBusy = atom<string | null>(null)
@@ -164,6 +169,7 @@ export function loadAgentPlugins(request: GatewayRequest, profile?: string | nul
}
$agentPlugins.set((result?.plugins ?? []).map(normalizeAgentPluginRow))
+ $agentPluginsProfile.set(scope)
$agentPluginsStatus.set('ready')
$agentPluginsError.set(null)
} catch (e) {
@@ -219,7 +225,8 @@ export async function toggleAgentPlugin(
const refreshed = result.plugin
- if (refreshed) {
+ // Patch only a list loaded for the profile this toggle targeted.
+ if (refreshed && $agentPluginsProfile.get() === (profile ?? null)) {
const snapshot = normalizeAgentPluginRow(refreshed)
$agentPlugins.set($agentPlugins.get().map(row => (row.key === key ? { ...row, ...snapshot } : row)))
@@ -472,11 +479,16 @@ export async function saveAgentPluginSettings(
throw new Error(opts.failMessage)
}
- if (result?.plugin) {
+ // The shared list may belong to another profile by now (a scope switch
+ // mid-save): only a list loaded for the profile this save targeted takes
+ // its refreshed row, and a refetch would hijack the other profile's view.
+ const ownsList = $agentPluginsProfile.get() === (opts.profile ?? null)
+
+ if (ownsList && result?.plugin) {
const refreshed = result.plugin
$agentPlugins.set($agentPlugins.get().map(row => (row.key === opts.key ? { ...row, ...refreshed } : row)))
- } else {
+ } else if (ownsList) {
await loadAgentPlugins(request, opts.profile)
}
diff --git a/website/docs/developer-guide/desktop-plugin-sdk.md b/website/docs/developer-guide/desktop-plugin-sdk.md
index c9eb8490d6b..c853f84c0a9 100644
--- a/website/docs/developer-guide/desktop-plugin-sdk.md
+++ b/website/docs/developer-guide/desktop-plugin-sdk.md
@@ -826,14 +826,16 @@ ctx.registerSettingsPage?.({
hosts. On those hosts, `ctx.register({ area: SETTINGS_PLUGINS_AREA, id, title,
render, data: { icon, children } })` is the same thing spelled out.
- Deep link: `host.navigate(pluginSettingsHref('<your-plugin-id>', 'units'))`
- (`/settings?tab=plugins&plugin=<id>&ppage=<sub-page>`).
+ (`/settings?tab=plugins&plugin=<id>&ppage=<sub-page>`). Sub-page ids are
+ yours: none is reserved.
- **Agent plugins get a page automatically.** A `config_schema` in
`plugin.yaml` renders as a form under Settings → Plugins, saved through
- `plugins.manage settings` for the profile the Settings scope selector targets.
- The gear on the plugin's Capabilities → Plugins row opens that page. In a
- unified package (agent half plus `desktop/plugin.js`), when the desktop half
- also registers a page, the schema form shows up as that entry's
- **Agent settings** sub-page, so the package has one entry.
+ `plugins.manage settings` for the profile the Settings scope selector targets
+ (`/settings?tab=plugins&agent=<key>`). The gear on the plugin's
+ Capabilities → Plugins row opens that page for the profile Capabilities has
+ selected. In a unified package (agent half plus `desktop/plugin.js`), when
+ the desktop half also registers a page, the schema form shows up as that
+ entry's **Agent settings** sub-page, so the package has one entry.
`src/plugins/hello-runtime/plugin.runtime.js` is a complete runtime example: one
page and two sub-pages, backed by `ctx.storage`.