Standardize Settings layout and save feedback (#2122)

* Group settings navigation menu

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Revert "Group settings navigation menu"

This reverts commit 5983a4e82074b8dab1084af1cadd803ba28ea65d.

* Standardize settings layout feedback

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Fix settings save status timer typing

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Retain settings save status

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Report color mode save state

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Match Appearance settings to two-column layout

Rebuild Appearance into Color mode & Theme, Localization, and Density & type sections with responsive two-column grids, consistent section headers, page description, and green save status.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Migrate settings pages to SettingsPageLayout and SettingsSection

Replace ScrollableOverlay/max-w-3xl shells with the shared settings
layout primitives across entity and static settings pages, normalize
section headers, and add settings.page.behavior.description locales.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Unify remaining settings pages on shared section chrome

Wire Appearance, Projects, and Remote Instances through SettingsSection/SettingsPageLayout so every settings surface shares the same header, divider, and page shell treatment.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Align settings UI with OpenChamber design system kit

Apply kit geometry and control specs: 840px content width, 32/48 padding, fixed 260/280 sidebars, radius/spacing tokens, settings select height, stepper dimensions, and shared field/link typography.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Migrate OpenChamberVisualSettings to shared settings primitives

Replace ad-hoc radio/checkbox/chip/field layouts with SettingsSection
shared chrome for Appearance, Density, Navigation, Chat/behavior, and
Privacy while preserving handlers and data-settings-item anchors.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Migrate settings pages to shared field/checkbox/radio primitives

Unify Defaults, Notifications, Behavior, Git, Session Retention, Passkeys,
OpenCode CLI, Commands, About, Keyboard Shortcuts, and Desktop Network on
SettingsFieldRow / SettingsCheckboxRow / SettingsRadioGroup / SettingsChipGroup
for consistent grid, spacing, and DRY layout. Also remove the GitPage double
SettingsSection wrap around GitHubSettings.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Unify remaining settings pages onto shared field primitives

Migrate Agents, Snippets, Skills, Usage, MCP identity rows and selects to
SettingsFieldRow/CheckboxRow/ChipGroup and SETTINGS_SELECT_*; align page
titles; light-touch Voice/Tunnel/Providers/Plugins without rewriting
complex OAuth, permissions, or tunnel flows.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Polish settings section dividers and transport helper text

Slightly stronger section borders for clearer group separation, and keep
message-stream transport description under the chip control.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Fix settings grid alignment, control heights, and Chat section titles

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Tighten settings grid: flat Chat 2x2 and full-width stacked selects

Message options use a flat two-column grid so row headers share a baseline.
Stacked selects fill their column; field-row selects keep a fixed sm:w-56 width.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Align mixed settings controls to shared FieldRow/CheckboxRow grid

Separate FieldRows from CheckboxRows with SettingsInset, move enum
radios into ControlGroups, and convert misplaced StackedFields to
full-width FieldRows so left edges no longer clash.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Translate Behavior response-style preset labels for es and pl

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Group settings nav into categories and improve icons/order

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Fix settings layout: fewer hrs, shared control widths, chat transport section

Remove SettingsInset top borders, align App install/Density controls to full cluster width, give Message Stream Transport its own Chat section, and fold Sessions Small Model into the first section to cut extra dividers.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Align Voice and MCP settings labels with shared heading classes

Swap form field labels to SETTINGS_FIELD_LABEL_CLASS and use
SettingsGroupTitle for MCP control-group headings (manual auth fallback,
request headers).

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Differentiate settings heading levels by context

Page titles are larger and quieter than section titles; group and field
labels use dedicated shared classes so hierarchy is consistent across
settings surfaces without ad-hoc typography mixes.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Use shared settings title classes in SettingsView home

Wire home and unavailable headings through the shared L1/L2 class
constants so they stay aligned with SettingsPageLayout.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Keep settings number steppers from stretching +/- buttons

Density & type NumberInputs no longer flex-grow across the row, and
NumberInput locks minus/plus to fixed width so the plus side cannot
inflate when the control is placed in a full-width cluster.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Place spacing and input-bar offset on their own row

Density & type now lays out as font families, then font sizes, then
Spacing Density / Input Bar Offset on the row below.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Regroup settings nav and improve Voice layout

Drop Advanced/Usage/Git nav categories: Voice and About under
Interface, Usage under OpenCode, Git under Workspace. Voice provider
chips and STT model cards use shared settings primitives with roomier
spacing and a two-column model grid.

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>

* Space out chat feature groups in visual settings

* Polish settings: save-state wiring, container-query layouts, unified dropdown triggers

- Wire shared save indicator into Behavior page saves and git identity CRUD
- Convert settings layout primitives and page rows from viewport to container
  queries so narrow panes stack instead of clipping
- Unify custom dropdown triggers (model/agent/provider pickers) and remaining
  page selects on the settings control size
- Bump global radius scale by 1px; align variant input with select size
- Migrate stray raw controls (MCP OAuth checkbox, worktree remove button,
  git identity dialog rows, skills dialog labels) onto shared primitives
- Make settings nav items span full sidebar width; trim nav to 240px

* Add General settings page, regroup nav, cap control widths, promote chat feature headers

* Mobile settings nav: plain background and touch-sized rows

* Hide secondary settings descriptions behind clickable info hints

* Move quota credentials to Usage, navigation settings to General, rename External Tunnel

* Quiet settings save indicator: silent success, delayed spinner, visible errors

* Rewrite settings-ui-patterns skill around shared primitives and refactored conventions

* Remove settings starter page; open last visited page, defaulting to General

* Settings polish: spacing, control sizes, trigger widths, readable model names, device dates

* Centralize dropdown trigger chrome, settings nav polish, mobile-only input bar offset

* Fix global line-height regression, auto-hide first-section divider, shortcut row spacing

* Global line-height 1.45, align scheduled tasks header button with select

* Hide editor toolbar and About in VS Code, animate chat render preview outside desktop dialog

* Rebuild agent tool permissions on source-of-truth model

Edit the agent's own permission map verbatim (inherit vs explicit actions, pattern rules only for pattern-capable keys), save permission-only, drop the server-side non-wildcard re-merge that resurrected deleted rules, and surface session-granted rules as read-only.

* Agents model parameters polish: row spacing, variant dropdown, unified widths, dash for unset numbers

---------

Co-authored-by: Serhii Dziupin <makeittech@users.noreply.github.com>
Co-authored-by: Bohdan Triapitsyn <artmore@protonmail.com>
This commit is contained in:
Serhii Dziupin
2026-07-18 00:11:05 +03:00
committed by GitHub
co-authored by Serhii Dziupin Bohdan Triapitsyn
parent 1b402fcb67
commit 17f1b24709
103 changed files with 6406 additions and 6110 deletions
@@ -0,0 +1,58 @@
import { describe, expect, test } from 'bun:test';
import { parsePermissionConfig, serializePermissionModel } from './agentPermissionModel';
const roundTrip = (config: unknown) => serializePermissionModel(parsePermissionConfig(config));
describe('agent permission source round-trip', () => {
test('null and empty configs stay unset', () => {
expect(roundTrip(null)).toBeNull();
expect(roundTrip(undefined)).toBeNull();
expect(roundTrip({})).toBeNull();
});
test('bare action string becomes the * key', () => {
expect(roundTrip('ask')).toEqual({ '*': 'ask' });
});
test('flat per-key actions survive verbatim', () => {
const config = { '*': 'allow', bash: 'ask', edit: 'deny' };
expect(roundTrip(config)).toEqual(config);
});
test('nested pattern maps survive verbatim, including wildcard inside', () => {
const config = {
'*': 'ask',
bash: { '*': 'ask', 'rm -rf *': 'deny', 'git status': 'allow' },
external_directory: { '/tmp/**': 'allow' },
};
expect(roundTrip(config)).toEqual(config);
});
test('pattern-only key without wildcard stays pattern-only (no synthesized default)', () => {
const config = { read: { '/secret/**': 'deny' } };
expect(roundTrip(config)).toEqual(config);
});
test('explicit allow is preserved — not conflated with unset', () => {
expect(roundTrip({ bash: 'allow' })).toEqual({ bash: 'allow' });
expect(roundTrip({ '*': 'allow' })).toEqual({ '*': 'allow' });
});
test('unknown junk values are dropped, valid siblings kept', () => {
expect(roundTrip({ bash: 'ask', broken: 42, worse: ['deny'] })).toEqual({ bash: 'ask' });
});
test('clearing everything serializes to null (key removed from config)', () => {
const model = parsePermissionConfig({ bash: 'ask' });
model.keys = {};
model.global = null;
expect(serializePermissionModel(model)).toBeNull();
});
test('blank patterns are not persisted', () => {
const model = parsePermissionConfig({});
model.keys.bash = { action: 'ask', patterns: [{ pattern: ' ', action: 'deny' }] };
expect(serializePermissionModel(model)).toEqual({ bash: 'ask' });
});
});
@@ -0,0 +1,504 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Icon } from '@/components/icon/Icon';
import { toast } from '@/components/ui';
import { cn } from '@/lib/utils';
import { useI18n } from '@/lib/i18n';
import { runtimeFetch } from '@/lib/runtime-fetch';
import { opencodeClient } from '@/lib/opencode/client';
import {
useAgentsStore,
getConfigDirectory,
type AgentWithExtras,
} from '@/stores/useAgentsStore';
import {
SettingsSection,
SettingsChipGroup,
SETTINGS_FIELD_LABEL_CLASS,
SETTINGS_HELPER_CLASS,
} from '@/components/sections/shared/SettingsSection';
import { SettingsInfoHint } from '@/components/sections/shared/SettingsInfoHint';
import {
ACTIONS,
cloneModel,
emptyModel,
isAction,
modelsEqual,
parsePermissionConfig,
serializePermissionModel,
type Action,
type EffectiveRule,
type PermissionModel,
} from './agentPermissionModel';
/**
* Source-of-truth permissions editor.
*
* This component edits EXACTLY the agent's own `permission` map as stored in
* its markdown frontmatter / opencode.json entry — never the resolved rules
* that `/agent` returns (those already include global config and one-off
* session grants, and writing them back is what used to corrupt configs).
*
* - "Inherit" means the key is absent from the agent's config; the effective
* action (from the resolved view) is shown as a hint.
* - Saving PATCHes only `{ permission }`, and the server writes it verbatim.
*/
/**
* Permission keys that exist beyond plain tool ids (virtual capabilities).
* Shown so they are discoverable; nothing is written unless set explicitly.
*/
const VIRTUAL_PERMISSION_KEYS = [
'edit',
'external_directory',
'doom_loop',
'plan_enter',
'plan_exit',
] as const;
/**
* Keys where opencode matches pattern rules (per docs: these accept either a
* bare action or a pattern map). Everything else is action-only — the pattern
* UI is hidden unless the config already contains patterns for the key.
*/
const PATTERN_CAPABLE_KEYS = new Set([
'read',
'edit',
'glob',
'grep',
'list',
'bash',
'task',
'external_directory',
'lsp',
'skill',
]);
/** Tool ids folded into broader permission keys — never shown standalone. */
const FOLDED_TOOL_IDS = new Set(['write', 'patch', 'apply_patch', 'multiedit', 'invalid']);
const formatKeyLabel = (key: string): string =>
key
.split(/[_-]/)
.filter(Boolean)
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
.join(' ');
interface AgentPermissionsEditorProps {
agent: AgentWithExtras;
}
export const AgentPermissionsEditor: React.FC<AgentPermissionsEditorProps> = ({ agent }) => {
const { t } = useI18n();
const updateAgent = useAgentsStore((state) => state.updateAgent);
const [baseline, setBaseline] = React.useState<PermissionModel>(emptyModel);
const [model, setModel] = React.useState<PermissionModel>(emptyModel);
const [isLoading, setIsLoading] = React.useState(true);
const [loadFailed, setLoadFailed] = React.useState(false);
const [isSaving, setIsSaving] = React.useState(false);
const [expandedKeys, setExpandedKeys] = React.useState<Record<string, boolean>>({});
const [toolIds, setToolIds] = React.useState<string[]>([]);
const [customKeyDraft, setCustomKeyDraft] = React.useState('');
const [reloadToken, setReloadToken] = React.useState(0);
const agentName = agent.name;
// --- Load the SOURCE permission map (the agent's own config file). ---
React.useEffect(() => {
let cancelled = false;
setIsLoading(true);
setLoadFailed(false);
void (async () => {
try {
const directory = getConfigDirectory();
const query = directory ? `?directory=${encodeURIComponent(directory)}` : '';
const response = await runtimeFetch(`/api/config/agents/${encodeURIComponent(agentName)}/config${query}`, {
headers: {
'Cache-Control': 'no-cache',
...(directory ? { 'x-opencode-directory': directory } : {}),
},
});
if (!response.ok) throw new Error(String(response.status));
const data = (await response.json().catch(() => null)) as { config?: { permission?: unknown } } | null;
if (cancelled) return;
const parsed = parsePermissionConfig(data?.config?.permission);
setBaseline(cloneModel(parsed));
setModel(parsed);
} catch {
if (!cancelled) setLoadFailed(true);
} finally {
if (!cancelled) setIsLoading(false);
}
})();
return () => {
cancelled = true;
};
}, [agentName, reloadToken]);
// --- Known tool ids for the key list (display only). ---
React.useEffect(() => {
let cancelled = false;
void (async () => {
try {
const ids = await opencodeClient.listToolIds({ directory: getConfigDirectory() });
if (!cancelled && Array.isArray(ids)) {
setToolIds(ids.filter((id) => typeof id === 'string' && !FOLDED_TOOL_IDS.has(id)));
}
} catch {
// tool ids are additive display data — the editor works without them
}
})();
return () => {
cancelled = true;
};
}, [agentName]);
// --- Effective rules from the resolved view (read-only hints). ---
const effectiveRules = React.useMemo<EffectiveRule[]>(() => {
const raw = (agent as { permission?: unknown }).permission;
if (!Array.isArray(raw)) return [];
const rules: EffectiveRule[] = [];
for (const entry of raw) {
if (!entry || typeof entry !== 'object') continue;
const { permission, pattern, action } = entry as Record<string, unknown>;
if (typeof permission === 'string' && typeof pattern === 'string' && isAction(action)) {
rules.push({ permission, pattern, action });
}
}
return rules;
}, [agent]);
const effectiveFor = React.useCallback((key: string): Action | null => {
const exact = effectiveRules.find((rule) => rule.permission === key && rule.pattern === '*');
if (exact) return exact.action;
const wildcard = effectiveRules.find((rule) => rule.permission === '*' && rule.pattern === '*');
return wildcard ? wildcard.action : null;
}, [effectiveRules]);
/** Session/runtime-granted rules that are NOT part of the saved config. */
const runtimeRulesFor = React.useCallback((key: string): EffectiveRule[] => {
const saved = model.keys[key]?.patterns ?? [];
const savedPatterns = new Set(saved.map((rule) => rule.pattern));
return effectiveRules.filter(
(rule) => rule.permission === key && rule.pattern !== '*' && !savedPatterns.has(rule.pattern),
);
}, [effectiveRules, model.keys]);
// --- Displayed key list: tools + virtual keys + anything set in the config. ---
const displayKeys = React.useMemo(() => {
const keys = new Set<string>();
for (const id of toolIds) keys.add(id);
for (const key of VIRTUAL_PERMISSION_KEYS) keys.add(key);
for (const key of Object.keys(model.keys)) keys.add(key);
// `edit` covers write/edit/apply_patch — the folded ids never show.
for (const folded of FOLDED_TOOL_IDS) keys.delete(folded);
return Array.from(keys).sort((a, b) => a.localeCompare(b));
}, [toolIds, model.keys]);
const isDirty = React.useMemo(() => !modelsEqual(model, baseline), [model, baseline]);
// --- Mutators ---
const setGlobal = (action: Action | null) => {
setModel((current) => ({ ...current, global: action }));
};
const setKeyAction = (key: string, action: Action | null) => {
setModel((current) => {
const next = cloneModel(current);
const state = next.keys[key] ?? { action: null, patterns: [] };
state.action = action;
if (state.action === null && state.patterns.length === 0) {
delete next.keys[key];
} else {
next.keys[key] = state;
}
return next;
});
};
const setPattern = (key: string, index: number, pattern: string, action: Action) => {
setModel((current) => {
const next = cloneModel(current);
const state = next.keys[key] ?? { action: null, patterns: [] };
state.patterns[index] = { pattern, action };
next.keys[key] = state;
return next;
});
};
const addPattern = (key: string) => {
setModel((current) => {
const next = cloneModel(current);
const state = next.keys[key] ?? { action: null, patterns: [] };
state.patterns.push({ pattern: '', action: 'allow' });
next.keys[key] = state;
return next;
});
setExpandedKeys((current) => ({ ...current, [key]: true }));
};
const removePattern = (key: string, index: number) => {
setModel((current) => {
const next = cloneModel(current);
const state = next.keys[key];
if (!state) return current;
state.patterns.splice(index, 1);
if (state.action === null && state.patterns.length === 0) {
delete next.keys[key];
}
return next;
});
};
const addCustomKey = () => {
const key = customKeyDraft.trim();
if (!key || key === '*') return;
setModel((current) => {
if (current.keys[key]) return current;
const next = cloneModel(current);
next.keys[key] = { action: 'ask', patterns: [] };
return next;
});
setExpandedKeys((current) => ({ ...current, [key]: true }));
setCustomKeyDraft('');
};
const handleSave = async () => {
setIsSaving(true);
try {
const permission = serializePermissionModel(model);
const result = await updateAgent(agentName, { permission });
if (result.ok) {
setBaseline(cloneModel(model));
toast.success(
result.requiresManualRestart
? t('settings.agents.page.permissionsEditor.toast.savedRestartRequired')
: t('settings.agents.page.permissionsEditor.toast.saved'),
);
} else {
toast.error(t('settings.agents.page.permissionsEditor.toast.saveFailed'));
}
} finally {
setIsSaving(false);
}
};
const handleDiscard = () => {
setModel(cloneModel(baseline));
};
const actionLabel = (action: Action): string => t(
action === 'allow'
? 'settings.agents.page.permissionsEditor.action.allow'
: action === 'ask'
? 'settings.agents.page.permissionsEditor.action.ask'
: 'settings.agents.page.permissionsEditor.action.deny',
);
const inheritLabel = t('settings.agents.page.permissionsEditor.action.inherit');
const defaultChipLabel = t('settings.agents.page.permissionsEditor.action.default');
const chipOptions = (unsetLabel?: string) => [
...(unsetLabel ? [{ value: 'inherit', label: unsetLabel }] : []),
...ACTIONS.map((action) => ({ value: action, label: actionLabel(action) })),
];
const renderActionChips = (
value: Action | null,
onChange: (action: Action | null) => void,
ariaLabel: string,
unsetLabel: string = inheritLabel,
) => (
<SettingsChipGroup
value={value ?? 'inherit'}
options={chipOptions(unsetLabel)}
onChange={(next) => onChange(next === 'inherit' ? null : (next as Action))}
aria-label={ariaLabel}
/>
);
if (isLoading) {
return (
<SettingsSection title={t('settings.agents.page.section.toolPermissions')}>
<p className={SETTINGS_HELPER_CLASS}>{t('common.loading')}</p>
</SettingsSection>
);
}
if (loadFailed) {
return (
<SettingsSection title={t('settings.agents.page.section.toolPermissions')}>
<div className="flex items-center gap-3">
<p className="typography-meta text-[var(--status-error)]">
{t('settings.agents.page.permissionsEditor.state.loadFailed')}
</p>
<Button variant="outline" size="xs" onClick={() => setReloadToken((token) => token + 1)}>
{t('settings.agents.page.permissionsEditor.actions.retry')}
</Button>
</div>
</SettingsSection>
);
}
return (
<SettingsSection
title={t('settings.agents.page.section.toolPermissions')}
settingsItem="agents.permissions"
info={t('settings.agents.page.permissionsEditor.sectionInfo')}
headerAction={isDirty ? (
<div className="flex items-center gap-2">
<Button variant="ghost" size="xs" className="!font-normal" onClick={handleDiscard} disabled={isSaving}>
{t('settings.agents.page.permissionsEditor.actions.discard')}
</Button>
<Button size="xs" className="!font-normal" onClick={() => void handleSave()} disabled={isSaving}>
{isSaving ? t('settings.common.actions.saving') : t('settings.agents.page.permissionsEditor.actions.save')}
</Button>
</div>
) : undefined}
contentClassName="space-y-4"
>
{/* Agent default (the `*` key) */}
<div className="flex flex-col gap-2 pb-2 @xl:flex-row @xl:items-center @xl:justify-between">
<div className="flex items-center gap-1.5">
<span className={SETTINGS_FIELD_LABEL_CLASS}>
{t('settings.agents.page.permissionsEditor.defaultLabel')}
</span>
<SettingsInfoHint>{t('settings.agents.page.permissionsEditor.defaultInfo')}</SettingsInfoHint>
{model.global === null && (
<span className="typography-micro text-muted-foreground">
{t('settings.agents.page.permissionsEditor.effectiveHint', { action: actionLabel(effectiveFor('*') ?? 'allow') })}
</span>
)}
</div>
{renderActionChips(model.global, setGlobal, t('settings.agents.page.permissionsEditor.defaultAria'), defaultChipLabel)}
</div>
<div>
{displayKeys.map((key) => {
const state = model.keys[key] ?? { action: null, patterns: [] };
const runtimeRules = runtimeRulesFor(key);
const supportsPatterns = PATTERN_CAPABLE_KEYS.has(key) || state.patterns.length > 0;
const hasDetails = supportsPatterns || runtimeRules.length > 0;
const isExpanded = expandedKeys[key] === true;
const effective = effectiveFor(key);
return (
<div key={key} className="border-t border-border/40 py-2">
<div className="flex flex-col gap-2 @xl:flex-row @xl:items-center @xl:justify-between">
<button
type="button"
onClick={hasDetails ? () => setExpandedKeys((current) => ({ ...current, [key]: !isExpanded })) : undefined}
className={cn('flex min-w-0 items-center gap-1.5 text-left', !hasDetails && 'cursor-default')}
aria-expanded={hasDetails ? isExpanded : undefined}
>
<Icon
name={isExpanded && hasDetails ? 'arrow-down-s' : 'arrow-right-s'}
className={cn('h-3.5 w-3.5 shrink-0 text-muted-foreground', !hasDetails && 'opacity-0')}
/>
<span className={SETTINGS_FIELD_LABEL_CLASS}>{formatKeyLabel(key)}</span>
<span className="typography-micro font-mono text-muted-foreground/70">{key}</span>
{state.action === null && effective !== null && (
<span className="typography-micro text-muted-foreground">
{t('settings.agents.page.permissionsEditor.effectiveHint', { action: actionLabel(effective) })}
</span>
)}
{state.patterns.length > 0 && (
<span className="typography-micro rounded bg-muted px-1 text-muted-foreground">
{t('settings.agents.page.permissionsEditor.ruleCount', { count: String(state.patterns.length) })}
</span>
)}
</button>
{renderActionChips(
state.action,
(action) => setKeyAction(key, action),
t('settings.agents.page.permissionsEditor.keyAria', { key }),
)}
</div>
{isExpanded && hasDetails && (
<div className="mt-2 space-y-2 pl-5">
{state.patterns.map((rule, index) => (
<div key={index} className="flex flex-wrap items-center gap-2">
<Input
value={rule.pattern}
onChange={(event) => setPattern(key, index, event.target.value, rule.action)}
placeholder={t('settings.agents.page.permissionsEditor.patternPlaceholder')}
className="h-8 w-full max-w-[24rem] min-w-0 flex-1 font-mono text-xs"
/>
<SettingsChipGroup
value={rule.action}
options={chipOptions()}
onChange={(next) => setPattern(key, index, rule.pattern, next as Action)}
aria-label={t('settings.agents.page.permissionsEditor.patternActionAria', { key })}
/>
<Button
variant="ghost"
size="icon"
className="h-7 w-7 shrink-0 text-muted-foreground hover:bg-destructive/10 hover:text-destructive"
onClick={() => removePattern(key, index)}
aria-label={t('settings.agents.page.permissionsEditor.actions.removeRuleAria')}
>
<Icon name="close" className="h-3.5 w-3.5" />
</Button>
</div>
))}
{supportsPatterns && (
<Button variant="outline" size="xs" className="!font-normal" onClick={() => addPattern(key)}>
<Icon name="add" className="mr-1 h-3.5 w-3.5" />
{t('settings.agents.page.permissionsEditor.actions.addRule')}
</Button>
)}
{runtimeRules.length > 0 && (
<div className="space-y-1 pt-1">
<div className="flex items-center gap-1.5">
<span className="typography-micro font-medium text-muted-foreground">
{t('settings.agents.page.permissionsEditor.sessionRulesTitle')}
</span>
<SettingsInfoHint>
{t('settings.agents.page.permissionsEditor.sessionRulesInfo')}
</SettingsInfoHint>
</div>
{runtimeRules.map((rule) => (
<div key={`${rule.pattern}-${rule.action}`} className="flex items-center gap-2">
<span className="typography-micro min-w-0 flex-1 truncate font-mono text-muted-foreground/70">
{rule.pattern}
</span>
<span className="typography-micro text-muted-foreground">{actionLabel(rule.action)}</span>
</div>
))}
</div>
)}
</div>
)}
</div>
);
})}
</div>
{/* Custom permission key */}
<div className="flex flex-wrap items-center gap-2 border-t border-border/40 pt-3">
<Input
value={customKeyDraft}
onChange={(event) => setCustomKeyDraft(event.target.value)}
onKeyDown={(event) => {
if (event.key === 'Enter') {
event.preventDefault();
addCustomKey();
}
}}
placeholder={t('settings.agents.page.permissionsEditor.customKeyPlaceholder')}
className="h-8 w-full max-w-[16rem] font-mono text-xs"
/>
<Button variant="outline" size="xs" className="!font-normal" onClick={addCustomKey} disabled={!customKeyDraft.trim()}>
<Icon name="add" className="mr-1 h-3.5 w-3.5" />
{t('settings.agents.page.permissionsEditor.actions.addKey')}
</Button>
</div>
</SettingsSection>
);
};
File diff suppressed because it is too large Load Diff
@@ -27,6 +27,7 @@ import { SettingsProjectSelector } from '@/components/sections/shared/SettingsPr
import { SidebarGroup } from '@/components/sections/shared/SidebarGroup';
import { Icon } from "@/components/icon/Icon";
import { useI18n } from '@/lib/i18n';
import { SETTINGS_PANEL_TITLE_CLASS } from '@/components/sections/shared/SettingsSection';
interface AgentsSidebarProps {
onItemSelect?: () => void;
@@ -350,7 +351,7 @@ export const AgentsSidebar: React.FC<AgentsSidebarProps> = ({ onItemSelect }) =>
return (
<div className={cn('flex h-full flex-col', bgClass)}>
<div className="border-b px-3 pt-4 pb-3">
<h2 className="text-base font-semibold text-foreground mb-3">{t('settings.agents.sidebar.title')}</h2>
<h2 className={`${SETTINGS_PANEL_TITLE_CLASS} mb-3`}>{t('settings.agents.sidebar.title')}</h2>
<SettingsProjectSelector className="mb-3" />
<div className="flex items-center justify-between gap-2">
<span className="typography-meta text-muted-foreground">{t('settings.agents.sidebar.total', { count: visibleAgents.length })}</span>
@@ -12,6 +12,7 @@ import { useOpenCodeReadiness } from '@/hooks/useOpenCodeReadiness';
import { useDeviceInfo } from '@/lib/device';
import { useI18n } from '@/lib/i18n';
import { cn } from '@/lib/utils';
import { dropdownTriggerVariants } from '@/components/ui/dropdown-trigger';
import { useConfigStore } from '@/stores/useConfigStore';
import { useUIStore } from '@/stores/useUIStore';
import { ModelPickerList, type ModelPickerEntry, type ModelPickerProvider } from '@/components/model-picker/ModelPickerList';
@@ -90,7 +91,15 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
}), [placeholder, t]);
const selectedModel = providerId && modelId ? { providerID: providerId, modelID: modelId } : null;
const triggerLabel = providerId && modelId ? `${providerId}/${modelId}` : (placeholder || t('settings.agents.modelSelector.notSelected'));
// Show the model's display name (as in the picker list), not the raw provider/model id.
const triggerLabel = React.useMemo(() => {
if (!providerId || !modelId) {
return placeholder || t('settings.agents.modelSelector.notSelected');
}
const provider = providers.find((entry) => entry.id === providerId);
const model = provider?.models?.find((entry) => entry.id === modelId);
return (typeof model?.name === 'string' && model.name.trim()) || modelId;
}, [modelId, placeholder, providerId, providers, t]);
const picker = (
<ModelPickerList
@@ -123,8 +132,8 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
onClick={isReady ? () => setIsMobilePanelOpen(true) : undefined}
disabled={!isReady}
className={cn(
'flex w-full items-center justify-between gap-2 rounded-lg border border-border/40 bg-[var(--surface-elevated)] px-2 py-1.5 text-left',
!isReady && 'opacity-60 cursor-not-allowed',
dropdownTriggerVariants(),
'w-full',
className,
)}
>
@@ -158,7 +167,8 @@ export const ModelSelector: React.FC<ModelSelectorProps> = ({
<DropdownMenu open={isReady && isDropdownOpen} onOpenChange={isReady ? setIsDropdownOpen : undefined}>
<DropdownMenuTrigger asChild>
<div className={cn(
'border-input data-[placeholder]:text-muted-foreground flex min-w-0 items-center justify-between gap-2 rounded-lg border bg-transparent px-2 py-2 typography-ui-label whitespace-nowrap shadow-none outline-none hover:bg-interactive-hover data-[popup-open]:bg-interactive-active h-6 w-fit',
dropdownTriggerVariants({ size: 'sm' }),
'min-w-0 w-fit',
!isReady && 'opacity-60 cursor-not-allowed',
className,
)}>
@@ -0,0 +1,97 @@
import type { PermissionConfig } from '@opencode-ai/sdk/v2';
/**
* Editor model for an agent's OWN `permission` map (the source config), with
* lossless parse/serialize between the persisted shape and the model.
* "null" action = key/pattern not set → inherited from global config/defaults.
*/
export type Action = 'allow' | 'ask' | 'deny';
export const ACTIONS: Action[] = ['allow', 'ask', 'deny'];
export interface KeyState {
/** Explicit action for the key's `*` pattern; null = not set (inherit). */
action: Action | null;
/** Non-wildcard pattern rules, in stable order. */
patterns: Array<{ pattern: string; action: Action }>;
}
export interface PermissionModel {
/** Explicit agent-level default (the `*` key); null = inherit. */
global: Action | null;
keys: Record<string, KeyState>;
}
/** Effective (resolved) rule as returned by /agent. */
export interface EffectiveRule {
permission: string;
pattern: string;
action: Action;
}
export const isAction = (value: unknown): value is Action =>
value === 'allow' || value === 'ask' || value === 'deny';
export const emptyModel = (): PermissionModel => ({ global: null, keys: {} });
/** Parse the persisted PermissionConfig into the editor model, verbatim. */
export const parsePermissionConfig = (config: unknown): PermissionModel => {
const model = emptyModel();
if (config == null) return model;
if (typeof config === 'string') {
if (isAction(config)) model.global = config;
return model;
}
if (typeof config !== 'object' || Array.isArray(config)) return model;
for (const [key, value] of Object.entries(config as Record<string, unknown>)) {
if (key === '*') {
if (isAction(value)) model.global = value;
continue;
}
const state: KeyState = { action: null, patterns: [] };
if (isAction(value)) {
state.action = value;
} else if (value && typeof value === 'object' && !Array.isArray(value)) {
for (const [pattern, action] of Object.entries(value as Record<string, unknown>)) {
if (!isAction(action)) continue;
if (pattern === '*') {
state.action = action;
} else {
state.patterns.push({ pattern, action });
}
}
} else {
continue;
}
model.keys[key] = state;
}
return model;
};
/** Serialize the editor model back to the persisted shape (canonical form). */
export const serializePermissionModel = (model: PermissionModel): PermissionConfig | null => {
const result: Record<string, Action | Record<string, Action>> = {};
if (model.global !== null) {
result['*'] = model.global;
}
for (const [key, state] of Object.entries(model.keys)) {
const patterns = state.patterns.filter((rule) => rule.pattern.trim().length > 0);
if (state.action !== null && patterns.length === 0) {
result[key] = state.action;
} else if (patterns.length > 0) {
const nested: Record<string, Action> = {};
if (state.action !== null) nested['*'] = state.action;
for (const rule of patterns) nested[rule.pattern] = rule.action;
result[key] = nested;
}
// action === null && no patterns → key omitted entirely (inherit)
}
return Object.keys(result).length > 0 ? (result as PermissionConfig) : null;
};
export const modelsEqual = (a: PermissionModel, b: PermissionModel): boolean =>
JSON.stringify(serializePermissionModel(a)) === JSON.stringify(serializePermissionModel(b));
export const cloneModel = (model: PermissionModel): PermissionModel =>
JSON.parse(JSON.stringify(model)) as PermissionModel;