feat(36-02): add shared scope picker module and wire ConnectView

This commit is contained in:
Jakub Zych
2026-11-24 19:40:02 +01:00
parent 3fd804e8c8
commit 6d7325e6d8
6 changed files with 1330 additions and 94 deletions

View File

@@ -0,0 +1,291 @@
// Pure domain logic for the 3-tier access selector and grouped ScopePicker
// shared by ConnectView and ApiTokenCreateDialog (Phase 36 UI-SPEC C1).
import type { AdminAPITokenScope } from '../api/types'
export type AccessTier = 'full' | 'read_only' | 'custom'
export type ScopeFilter = 'all' | 'selected' | 'read_only'
export interface ScopeGroup {
key: string
pluginId: string
label: string
scopes: AdminAPITokenScope[]
}
export interface CustomScopeSelection {
adminRead: boolean
scopes: ReadonlySet<string>
}
export interface ScopeSummaryChip {
key: string
name: string
label: string
kind: 'admin_read' | 'write' | 'read_only'
}
export interface PartitionedCatalog {
fullScope: AdminAPITokenScope | null
adminReadScope: AdminAPITokenScope | null
pluginScopes: AdminAPITokenScope[]
}
export interface SummaryModel {
chips: ScopeSummaryChip[]
visible: ScopeSummaryChip[]
overflowCount: number
selectedWriteCount: number
selectedPluginCount: number
distinctPluginCount: number
}
export interface InitialScopeState {
tier: AccessTier
custom: {
adminRead: boolean
scopes: Set<string>
}
}
/** Splits a scope catalog into framework tiers (*, admin:read) and plugin scopes. */
export function partitionCatalog(catalog: readonly AdminAPITokenScope[]): PartitionedCatalog {
let fullScope: AdminAPITokenScope | null = null
let adminReadScope: AdminAPITokenScope | null = null
const pluginScopes: AdminAPITokenScope[] = []
for (const scope of catalog) {
if (scope.name === '*') {
fullScope ??= scope
} else if (scope.name === 'admin:read') {
adminReadScope ??= scope
} else {
pluginScopes.push(scope)
}
}
return { fullScope, adminReadScope, pluginScopes }
}
/**
* Groups plugin scopes into flat sections keyed by (plugin_id, group) so two
* plugins never collide even when they resolve to the same translated label
* (D-17). Intra-group order preserves the server catalog order; groups sort
* alphabetically by label using locale-aware collation, tie-broken on plugin_id.
*/
export function groupPluginScopes(
pluginScopes: readonly AdminAPITokenScope[],
locale: string,
fallbackGroupLabel: string,
): ScopeGroup[] {
const byKey = new Map<string, ScopeGroup>()
for (const scope of pluginScopes) {
const key = `${scope.plugin_id}\0${scope.group}`
let group = byKey.get(key)
if (!group) {
const label = scope.group.trim() || scope.plugin_id.trim() || fallbackGroupLabel
group = {
key,
pluginId: scope.plugin_id,
label,
scopes: [],
}
byKey.set(key, group)
}
group.scopes.push(scope)
}
let collator: Intl.Collator
try {
collator = new Intl.Collator(locale || undefined, { sensitivity: 'base' })
} catch {
collator = new Intl.Collator(undefined, { sensitivity: 'base' })
}
return [...byKey.values()].sort((a, b) => {
const byLabel = collator.compare(a.label, b.label)
if (byLabel !== 0) {
return byLabel
}
const byPlugin = a.pluginId.localeCompare(b.pluginId)
if (byPlugin !== 0) {
return byPlugin
}
return a.key.localeCompare(b.key)
})
}
/** Case-insensitive substring search across scope code, label, description, plugin_id, and group label. */
export function matchesScopeQuery(scope: AdminAPITokenScope, groupLabel: string, query: string): boolean {
const normalized = query.trim().toLowerCase()
if (normalized === '') {
return true
}
return (
scope.name.toLowerCase().includes(normalized) ||
scope.label.toLowerCase().includes(normalized) ||
scope.description.toLowerCase().includes(normalized) ||
scope.plugin_id.toLowerCase().includes(normalized) ||
groupLabel.toLowerCase().includes(normalized)
)
}
/** True when a plugin scope is ticked directly or covered via the opt-in admin:read toggle (D-04). */
export function isEffectivelySelected(scope: AdminAPITokenScope, selection: CustomScopeSelection): boolean {
return selection.scopes.has(scope.name) || (selection.adminRead && scope.read_only)
}
/**
* Smart accordion expand defaults (D-07):
* - Searching: expand every matching group.
* - Small catalog (<= 3 groups or <= 12 plugin scopes): expand all groups.
* - Larger catalog: expand only groups with at least one effectively selected scope.
*/
export function computeDefaultExpanded(
groups: readonly ScopeGroup[],
totalPluginScopes: number,
selection: CustomScopeSelection,
searching: boolean,
): Set<string> {
if (searching || groups.length <= 3 || totalPluginScopes <= 12) {
return new Set(groups.map((group) => group.key))
}
const expanded = new Set<string>()
for (const group of groups) {
if (group.scopes.some((scope) => isEffectivelySelected(scope, selection))) {
expanded.add(group.key)
}
}
return expanded
}
/**
* Builds the elevated-first Custom summary model (D-06):
* 1. admin:read chip (if enabled and present in catalog)
* 2. Selected write scopes (non-read_only) in catalog order
* 3. Selected read-only scopes in catalog order, only when admin:read is OFF
*/
export function buildSummaryModel(
catalog: readonly AdminAPITokenScope[],
selection: CustomScopeSelection,
maxVisible = 6,
): SummaryModel {
const { adminReadScope, pluginScopes } = partitionCatalog(catalog)
const adminReadActive = selection.adminRead && adminReadScope !== null
const chips: ScopeSummaryChip[] = []
if (adminReadActive) {
chips.push({
key: 'admin:read',
name: 'admin:read',
label: 'admin:read',
kind: 'admin_read',
})
}
const selectedWrites: AdminAPITokenScope[] = []
const selectedReads: AdminAPITokenScope[] = []
for (const scope of pluginScopes) {
if (!selection.scopes.has(scope.name)) {
continue
}
if (!scope.read_only) {
selectedWrites.push(scope)
} else if (!adminReadActive) {
selectedReads.push(scope)
}
}
for (const scope of selectedWrites) {
chips.push({
key: scope.name,
name: scope.name,
label: scope.label,
kind: 'write',
})
}
for (const scope of selectedReads) {
chips.push({
key: scope.name,
name: scope.name,
label: scope.label,
kind: 'read_only',
})
}
const countedScopes = adminReadActive ? selectedWrites : [...selectedWrites, ...selectedReads]
const pluginKeys = new Set<string>()
for (const scope of countedScopes) {
pluginKeys.add(scope.plugin_id || scope.group || scope.name)
}
const cap = Math.max(0, maxVisible)
const visible = chips.slice(0, cap)
const overflowCount = Math.max(0, chips.length - cap)
return {
chips,
visible,
overflowCount,
selectedWriteCount: selectedWrites.length,
selectedPluginCount: countedScopes.length,
distinctPluginCount: pluginKeys.size,
}
}
/**
* Serializes the active tier/custom selection into the exact scope list submitted
* to POST /mcp/consent/{request} or POST /account/tokens (D-04, T-36-04).
*/
export function computeSubmittedScopes(
tier: AccessTier,
catalog: readonly AdminAPITokenScope[],
custom: CustomScopeSelection,
): string[] {
const { fullScope, adminReadScope, pluginScopes } = partitionCatalog(catalog)
if (tier === 'full') {
return fullScope ? ['*'] : []
}
if (tier === 'read_only') {
return adminReadScope ? ['admin:read'] : []
}
if (custom.adminRead && adminReadScope) {
return [
'admin:read',
...pluginScopes.filter((scope) => !scope.read_only && custom.scopes.has(scope.name)).map((scope) => scope.name),
]
}
return pluginScopes.filter((scope) => custom.scopes.has(scope.name)).map((scope) => scope.name)
}
/** Resolves the initial tier and Custom selection for ConnectView (D-03) or ApiTokenCreateDialog (D-08). */
export function resolveInitialState(
catalog: readonly AdminAPITokenScope[],
mode: 'connect' | 'token',
): InitialScopeState {
const { fullScope, adminReadScope, pluginScopes } = partitionCatalog(catalog)
if (mode === 'connect') {
if (adminReadScope !== null) {
return { tier: 'read_only', custom: { adminRead: false, scopes: new Set() } }
}
if (pluginScopes.length > 0) {
return {
tier: 'custom',
custom: { adminRead: false, scopes: new Set(pluginScopes.map((scope) => scope.name)) },
}
}
if (fullScope !== null) {
return { tier: 'full', custom: { adminRead: false, scopes: new Set() } }
}
return { tier: 'read_only', custom: { adminRead: false, scopes: new Set() } }
}
if (adminReadScope !== null) {
return { tier: 'read_only', custom: { adminRead: false, scopes: new Set() } }
}
if (fullScope !== null) {
return { tier: 'full', custom: { adminRead: false, scopes: new Set() } }
}
return { tier: 'custom', custom: { adminRead: false, scopes: new Set() } }
}