The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): the Connectors page replaces the MCP tab (#119074)
Siddharth Balyandc50403a81d1
diff --git a/.gitignore b/.gitignoreindex 63c2583b769..227ac9ac973 100644--- a/.gitignore+++ b/.gitignore@@ -35,6 +35,9 @@ data/# Bundled community plugin index seed (shipped as package data) — the bare# `data/` pattern above would otherwise swallow it.!hermes_cli/data/+# The Connectors page's wire layer (apps/desktop/src/app/capabilities/connectors/data/)+# — same reason: the bare `data/` pattern above would otherwise swallow it.+!apps/desktop/src/app/capabilities/connectors/data/.pytest_cache/test_durations.json.pytest-cache/diff --git a/apps/desktop/src/app/capabilities/connectors/add-dialog.tsx b/apps/desktop/src/app/capabilities/connectors/add-dialog.tsxnew file mode 100644index 00000000000..f9ad6342b44--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/add-dialog.tsx@@ -0,0 +1,124 @@+import { useState } from 'react'++import { Button } from '@/components/ui/button'+import { Dialog, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'+import type { ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'+import { notifyError } from '@/store/notifications'++import { McpJsonEditor } from '../mcp/mcp-editor'+import type { McpServersController } from '../mcp/use-mcp-servers'++import { type AddServerDraft, EMPTY_ADD_DRAFT, entryOfDraft, isDraftComplete } from './add-server-draft'+import { AddServerForm } from './add-server-form'+import { setMcpBearerToken } from './data/rpc'++export interface AddServerDialogProps {+ controller: McpServersController+ onOpenChange: (open: boolean) => void+ open: boolean+ profile: ProfileScope+}++export function AddServerDialog({ controller, onOpenChange, open, profile }: AddServerDialogProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage.add+ const [draft, setDraft] = useState<AddServerDraft>(EMPTY_ADD_DRAFT)+ const [raw, setRaw] = useState(false)+ const [saving, setSaving] = useState(false)++ const name = draft.name.trim()+ const nameTaken = name !== '' && name in controller.servers++ const discardRawDraft = () => {+ if (controller.dirty) {+ controller.resetDraft(controller.servers)+ }+ }++ const close = () => {+ discardRawDraft()+ setDraft(EMPTY_ADD_DRAFT)+ setRaw(false)+ onOpenChange(false)+ }++ const openRaw = () => {+ controller.addServer()+ setRaw(true)+ }++ const leaveRaw = () => {+ discardRawDraft()+ setRaw(false)+ }++ const save = async () => {+ setSaving(true)++ try {+ if (!(await controller.addServerEntry(name, entryOfDraft(draft)))) {+ return+ }++ if (draft.transport === 'http' && draft.auth === 'bearer' && draft.bearer.trim() !== '') {+ await setMcpBearerToken(profile, name, draft.bearer.trim())+ controller.refetchConfig()+ }++ close()+ } catch (err) {+ notifyError(err, copy.saveFailed)+ } finally {+ setSaving(false)+ }+ }++ return (+ <Dialog onOpenChange={next => (next ? onOpenChange(true) : close())} open={open}>+ <DialogContent+ bodyClassName="gap-0 overflow-hidden p-0"+ className={raw ? 'h-[min(40rem,80vh)] min-w-[min(48rem,90vw)]' : 'max-h-[min(44rem,85vh)] min-w-[min(34rem,90vw)]'}+ fitContent+ >+ <header className="flex shrink-0 items-center border-b border-(--ui-stroke-tertiary) px-5 py-3">+ <DialogTitle className="text-base font-semibold">{copy.title}</DialogTitle>+ </header>+ <DialogDescription className="sr-only">{copy.hint}</DialogDescription>++ {raw ? (+ <div className="flex min-h-0 flex-1 flex-col">+ <McpJsonEditor controller={controller} />+ </div>+ ) : (+ <div className="min-h-0 flex-1 overflow-y-auto px-5 py-4">+ <AddServerForm draft={draft} nameTaken={nameTaken} onChange={setDraft} />+ </div>+ )}++ <footer className="flex shrink-0 items-center gap-2 border-t border-(--ui-stroke-tertiary) px-5 py-3">+ {raw ? (+ <Button onClick={leaveRaw} size="sm" variant="outline">+ {t.common.back}+ </Button>+ ) : (+ <>+ <Button onClick={openRaw} size="sm" variant="outline">+ {copy.editJson}+ </Button>+ <Button+ className="ml-auto"+ disabled={saving || nameTaken || !isDraftComplete(draft) || controller.profilePending}+ loading={saving}+ onClick={() => void save()}+ size="sm"+ >+ {saving ? t.common.saving : t.common.save}+ </Button>+ </>+ )}+ </footer>+ </DialogContent>+ </Dialog>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/add-server-draft.ts b/apps/desktop/src/app/capabilities/connectors/add-server-draft.tsnew file mode 100644index 00000000000..e2d069036ef--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/add-server-draft.ts@@ -0,0 +1,151 @@+import { type McpServerEntry, normalizeEntry } from '@/lib/mcp-servers'++export type AddServerAuth = 'bearer' | 'none' | 'oauth'++export type AddServerTransport = 'http' | 'stdio'++export interface DraftValue {+ id: number+ value: string+}++export interface DraftPair {+ id: number+ key: string+ value: string+}++export interface AddServerDraft {+ args: DraftValue[]+ auth: AddServerAuth+ bearer: string+ command: string+ cwd: string+ env: DraftPair[]+ headers: DraftPair[]+ name: string+ passthrough: DraftValue[]+ transport: AddServerTransport+ url: string+}++let rowCounter = 0++export const nextRowId = (): number => ++rowCounter++export const emptyValue = (value = ''): DraftValue => ({ id: nextRowId(), value })++export const emptyPair = (key = '', value = ''): DraftPair => ({ id: nextRowId(), key, value })++export const EMPTY_ADD_DRAFT: AddServerDraft = {+ args: [],+ auth: 'none',+ bearer: '',+ command: '',+ cwd: '',+ env: [],+ headers: [],+ name: '',+ passthrough: [],+ transport: 'stdio',+ url: ''+}++export const isDraftComplete = (draft: AddServerDraft): boolean =>+ draft.name.trim() !== '' && (draft.transport === 'stdio' ? draft.command.trim() !== '' : draft.url.trim() !== '')++const filledPairs = (rows: readonly DraftPair[]): Record<string, string> =>+ Object.fromEntries(rows.filter(row => row.key.trim() !== '').map(row => [row.key.trim(), row.value]))++const filledValues = (rows: readonly DraftValue[]): string[] =>+ rows.map(row => row.value.trim()).filter(value => value !== '')++const envReference = (name: string): string => `\${${name}}`++function httpEntry(draft: AddServerDraft): McpServerEntry {+ const headers = filledPairs(draft.headers)+ const entry: McpServerEntry = { url: draft.url.trim() }++ if (Object.keys(headers).length > 0) {+ entry.headers = headers+ }++ if (draft.auth === 'oauth') {+ entry.auth = 'oauth'+ }++ return entry+}++function stdioEntry(draft: AddServerDraft): McpServerEntry {+ const env = { ...filledPairs(draft.env) }++ for (const name of filledValues(draft.passthrough)) {+ env[name] = envReference(name)+ }++ const args = filledValues(draft.args)+ const entry: McpServerEntry = { command: draft.command.trim() }++ if (args.length > 0) {+ entry.args = args+ }++ if (Object.keys(env).length > 0) {+ entry.env = env+ }++ if (draft.cwd.trim() !== '') {+ entry.cwd = draft.cwd.trim()+ }++ return entry+}++export const entryOfDraft = (draft: AddServerDraft): McpServerEntry =>+ draft.transport === 'http' ? httpEntry(draft) : stdioEntry(draft)++type EntryValue = McpServerEntry[string]++const isString = (value: EntryValue): value is string => Object.prototype.toString.call(value) === '[object String]'++const asString = (value: EntryValue): string => (isString(value) ? value : '')++const asRecord = (value: EntryValue): McpServerEntry =>+ value instanceof Object && !Array.isArray(value) ? Object.fromEntries(Object.entries(value)) : {}++const asValues = (value: EntryValue): DraftValue[] =>+ Array.isArray(value) ? value.map((entry: EntryValue) => emptyValue(asString(entry))) : []++const forwarded = (key: string, value: EntryValue): boolean => value === envReference(key)++export function draftFromEntry(name: string, raw: McpServerEntry, previous: AddServerDraft): AddServerDraft {+ const entry = normalizeEntry(raw)+ const url = asString(entry.url)+ const named = name || previous.name++ if (url !== '') {+ return {+ ...EMPTY_ADD_DRAFT,+ auth: asString(entry.auth) === 'oauth' ? 'oauth' : 'none',+ bearer: previous.bearer,+ headers: Object.entries(asRecord(entry.headers)).map(([key, value]) => emptyPair(key, asString(value))),+ name: named,+ transport: 'http',+ url+ }+ }++ const env = Object.entries(asRecord(entry.env))++ return {+ ...EMPTY_ADD_DRAFT,+ args: asValues(entry.args),+ command: asString(entry.command),+ cwd: asString(entry.cwd),+ env: env.filter(([key, value]) => !forwarded(key, value)).map(([key, value]) => emptyPair(key, asString(value))),+ name: named,+ passthrough: env.filter(([key, value]) => forwarded(key, value)).map(([key]) => emptyValue(key)),+ transport: 'stdio'+ }+}diff --git a/apps/desktop/src/app/capabilities/connectors/add-server-form.tsx b/apps/desktop/src/app/capabilities/connectors/add-server-form.tsxnew file mode 100644index 00000000000..e10630e7d3b--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/add-server-form.tsx@@ -0,0 +1,326 @@+import { type ReactNode, useState } from 'react'++import { Button } from '@/components/ui/button'+import { Codicon } from '@/components/ui/codicon'+import { Input } from '@/components/ui/input'+import { SegmentedControl } from '@/components/ui/segmented-control'+import { Textarea } from '@/components/ui/textarea'+import { useI18n } from '@/i18n'+import type { Translations } from '@/i18n/types'+import { parseMcpImport } from '@/lib/mcp-import'++import {+ type AddServerAuth,+ type AddServerDraft,+ type AddServerTransport,+ draftFromEntry,+ type DraftPair,+ type DraftValue,+ emptyPair,+ emptyValue+} from './add-server-draft'++type AddCopy = Translations['connectorsPage']['add']++type SetDraft = (patch: Partial<AddServerDraft>) => void++export interface AddServerFormProps {+ draft: AddServerDraft+ nameTaken: boolean+ onChange: (next: AddServerDraft) => void+}++export function AddServerForm({ draft, nameTaken, onChange }: AddServerFormProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage.add+ const set: SetDraft = patch => onChange({ ...draft, ...patch })++ return (+ <div className="grid gap-4" data-slot="add-server-form">+ <PasteBox copy={copy} onFill={onChange} previous={draft} />++ <Field label={copy.name}>+ <Input onChange={event => set({ name: event.currentTarget.value })} size="sm" value={draft.name} />+ {nameTaken ? <p className="text-[0.65rem] text-(--ui-red)">{copy.nameTaken}</p> : null}+ </Field>++ <Fieldset label={copy.type}>+ <SegmentedControl+ onChange={(next: AddServerTransport) => set({ transport: next })}+ options={[+ { id: 'stdio', label: copy.typeStdio },+ { id: 'http', label: copy.typeHttp }+ ]}+ value={draft.transport}+ />+ </Fieldset>++ {draft.transport === 'stdio' ? (+ <StdioFields copy={copy} draft={draft} set={set} />+ ) : (+ <HttpFields copy={copy} draft={draft} set={set} />+ )}+ </div>+ )+}++function StdioFields({ copy, draft, set }: { copy: AddCopy; draft: AddServerDraft; set: SetDraft }) {+ return (+ <>+ <Field label={copy.command}>+ <Input onChange={event => set({ command: event.currentTarget.value })} size="sm" value={draft.command} />+ </Field>++ <ValueRows+ addLabel={copy.addArg}+ label={copy.args}+ onChange={args => set({ args })}+ removeLabel={copy.removeRow}+ rows={draft.args}+ />++ <PairRows+ addLabel={copy.addEnvVar}+ copy={copy}+ label={copy.envVars}+ onChange={env => set({ env })}+ rows={draft.env}+ />++ <ValueRows+ addLabel={copy.addPassthrough}+ label={copy.passthrough}+ onChange={passthrough => set({ passthrough })}+ placeholder={copy.keyPlaceholder}+ removeLabel={copy.removeRow}+ rows={draft.passthrough}+ />++ <Field label={copy.cwd}>+ <Input onChange={event => set({ cwd: event.currentTarget.value })} size="sm" value={draft.cwd} />+ </Field>+ </>+ )+}++const AUTH_OPTIONS: readonly AddServerAuth[] = ['none', 'oauth', 'bearer']++function HttpFields({ copy, draft, set }: { copy: AddCopy; draft: AddServerDraft; set: SetDraft }) {+ const authLabel = { bearer: copy.authBearer, none: copy.authNone, oauth: copy.authOauth }++ return (+ <>+ <Field label={copy.url}>+ <Input onChange={event => set({ url: event.currentTarget.value })} size="sm" value={draft.url} />+ </Field>++ <PairRows+ addLabel={copy.addHeader}+ copy={copy}+ label={copy.headers}+ onChange={headers => set({ headers })}+ rows={draft.headers}+ />++ <Fieldset label={copy.auth}>+ <SegmentedControl+ onChange={(next: AddServerAuth) => set({ auth: next })}+ options={AUTH_OPTIONS.map(id => ({ id, label: authLabel[id] }))}+ value={draft.auth}+ />+ </Fieldset>++ {draft.auth === 'bearer' ? (+ <Field label={copy.authBearer}>+ <Input+ onChange={event => set({ bearer: event.currentTarget.value })}+ size="sm"+ type="password"+ value={draft.bearer}+ />+ </Field>+ ) : null}+ </>+ )+}++function PasteBox({+ copy,+ onFill,+ previous+}: {+ copy: AddCopy+ onFill: (next: AddServerDraft) => void+ previous: AddServerDraft+}) {+ const [text, setText] = useState('')+ const [failed, setFailed] = useState(false)++ const read = (value: string) => {+ setText(value)++ if (value.trim() === '') {+ setFailed(false)++ return+ }++ const entries = parseMcpImport(value)++ setFailed(entries === null)++ if (entries !== null) {+ onFill(draftFromEntry(entries[0].name, entries[0].config, previous))+ }+ }++ return (+ <Fieldset label={copy.pasteLabel}>+ <Textarea+ aria-label={copy.pasteLabel}+ className="max-h-32 min-h-16 font-mono text-[0.68rem]"+ onChange={event => read(event.currentTarget.value)}+ placeholder={copy.pastePlaceholder}+ value={text}+ />+ {failed ? <p className="text-[0.65rem] text-(--ui-text-tertiary)">{copy.pasteNoMatch}</p> : null}+ </Fieldset>+ )+}++function FieldLabel({ children }: { children: string }) {+ return <span className="text-xs font-medium text-(--ui-text-primary)">{children}</span>+}++function Field({ children, label }: { children: ReactNode; label: string }) {+ return (+ <label className="grid gap-1.5">+ <FieldLabel>{label}</FieldLabel>+ {children}+ </label>+ )+}++function Fieldset({ children, label }: { children: ReactNode; label: string }) {+ return (+ <div aria-label={label} className="grid gap-1.5" role="group">+ <FieldLabel>{label}</FieldLabel>+ {children}+ </div>+ )+}++function TrashButton({ label, onClick }: { label: string; onClick: () => void }) {+ return (+ <Button+ aria-label={label}+ className="shrink-0 text-(--ui-text-tertiary)"+ onClick={onClick}+ size="icon-xs"+ variant="ghost"+ >+ <Codicon name="trash" size="0.8125rem" />+ </Button>+ )+}++function RowsFrame({+ addLabel,+ children,+ label,+ onAdd+}: {+ addLabel: string+ children: ReactNode+ label: string+ onAdd: () => void+}) {+ return (+ <Fieldset label={label}>+ {children}+ <Button className="justify-self-start" onClick={onAdd} size="xs" variant="text">+ {addLabel}+ </Button>+ </Fieldset>+ )+}++function ValueRows({+ addLabel,+ label,+ onChange,+ placeholder,+ removeLabel,+ rows+}: {+ addLabel: string+ label: string+ onChange: (rows: DraftValue[]) => void+ placeholder?: string+ removeLabel: string+ rows: DraftValue[]+}) {+ const replace = (row: DraftValue, value: string) =>+ onChange(rows.map(candidate => (candidate.id === row.id ? { ...row, value } : candidate)))++ return (+ <RowsFrame addLabel={addLabel} label={label} onAdd={() => onChange([...rows, emptyValue()])}>+ {rows.map(row => (+ <div className="flex items-center gap-1.5" key={row.id}>+ <Input+ aria-label={label}+ className="min-w-0 flex-1"+ onChange={event => replace(row, event.currentTarget.value)}+ placeholder={placeholder}+ size="sm"+ value={row.value}+ />+ <TrashButton label={removeLabel} onClick={() => onChange(rows.filter(other => other.id !== row.id))} />+ </div>+ ))}+ </RowsFrame>+ )+}++function PairRows({+ addLabel,+ copy,+ label,+ onChange,+ rows+}: {+ addLabel: string+ copy: AddCopy+ label: string+ onChange: (rows: DraftPair[]) => void+ rows: DraftPair[]+}) {+ const patch = (row: DraftPair, next: Partial<DraftPair>) =>+ onChange(rows.map(candidate => (candidate.id === row.id ? { ...row, ...next } : candidate)))++ return (+ <RowsFrame addLabel={addLabel} label={label} onAdd={() => onChange([...rows, emptyPair()])}>+ {rows.map(row => (+ <div className="flex items-center gap-1.5" key={row.id}>+ <Input+ aria-label={copy.keyPlaceholder}+ className="min-w-0 flex-1"+ onChange={event => patch(row, { key: event.currentTarget.value })}+ placeholder={copy.keyPlaceholder}+ size="sm"+ value={row.key}+ />+ <Input+ aria-label={copy.valuePlaceholder}+ className="min-w-0 flex-1"+ onChange={event => patch(row, { value: event.currentTarget.value })}+ placeholder={copy.valuePlaceholder}+ size="sm"+ value={row.value}+ />+ <TrashButton label={copy.removeRow} onClick={() => onChange(rows.filter(other => other.id !== row.id))} />+ </div>+ ))}+ </RowsFrame>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/catalog-mark.tsx b/apps/desktop/src/app/capabilities/connectors/catalog-mark.tsxnew file mode 100644index 00000000000..53e78adfb4c--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/catalog-mark.tsx@@ -0,0 +1,21 @@+import { Codicon } from '@/components/ui/codicon'+import { Tip } from '@/components/ui/tooltip'+import { useI18n } from '@/i18n'+import { cn } from '@/lib/utils'++export function CatalogMark({ className }: { className?: string }) {+ const { t } = useI18n()+ const label = t.connectorsPage.card.inCatalog++ return (+ <Tip label={label}>+ <span+ aria-label={label}+ className={cn('relative z-10 flex shrink-0 items-center text-(--ui-text-quaternary)', className)}+ role="img"+ >+ <Codicon name="verified-filled" size="0.75rem" />+ </span>+ </Tip>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/category-picker.tsx b/apps/desktop/src/app/capabilities/connectors/category-picker.tsxnew file mode 100644index 00000000000..bd201e5134b--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/category-picker.tsx@@ -0,0 +1,74 @@+import { useRef, useState } from 'react'++import { Codicon } from '@/components/ui/codicon'+import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from '@/components/ui/command'+import { controlVariants } from '@/components/ui/control'+import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover'+import { useI18n } from '@/i18n'+import { cn } from '@/lib/utils'++import { categoryLabel, type CountedValue, UNCATEGORISED } from './derive-tools'++export interface CategoryPickerProps {+ categories: CountedValue[]+ onChange: (category: null | string) => void+ value: null | string+}++export function CategoryPicker({ categories, onChange, value }: CategoryPickerProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage+ const labelFor = (name: string) => (name === UNCATEGORISED ? copy.uncategorised : categoryLabel(name))+ const selected = value === null ? null : categories.find(entry => entry.value === value)+ const [open, setOpen] = useState(false)+ const trigger = useRef<HTMLButtonElement>(null)++ const pick = (next: null | string) => {+ onChange(next)+ setOpen(false)+ trigger.current?.focus()+ }++ return (+ <Popover onOpenChange={setOpen} open={open}>+ <PopoverTrigger asChild>+ <button+ aria-expanded={open}+ aria-haspopup="listbox"+ className={cn(controlVariants({ size: 'xs' }), 'flex w-auto items-center gap-1.5 whitespace-nowrap')}+ ref={trigger}+ type="button"+ >+ <span className="truncate">+ {selected ? labelFor(selected.value) : copy.tools.categorySelect(categories.length)}+ </span>+ <Codicon className="shrink-0 opacity-60" name="chevron-down" size="0.875rem" />+ </button>+ </PopoverTrigger>+ <PopoverContent align="start" className="min-w-(--radix-popover-trigger-width) p-0">+ <Command>+ <CommandInput autoFocus placeholder={copy.filterCategory} />+ <CommandList>+ <CommandEmpty>{copy.tools.noMatch}</CommandEmpty>+ <CommandGroup>+ <CommandItem onSelect={() => pick(null)} value={copy.categoryAll}>+ <Codicon className={cn('mr-2 size-4', value === null ? 'opacity-100' : 'opacity-0')} name="check" />+ {copy.categoryAll}+ </CommandItem>+ {categories.map(entry => (+ <CommandItem key={entry.value} onSelect={() => pick(entry.value)} value={labelFor(entry.value)}>+ <Codicon+ className={cn('mr-2 size-4', entry.value === value ? 'opacity-100' : 'opacity-0')}+ name="check"+ />+ <span className="min-w-0 flex-1 truncate">{labelFor(entry.value)}</span>+ <span className="ml-2 shrink-0 tabular-nums text-(--ui-text-tertiary)">{entry.count}</span>+ </CommandItem>+ ))}+ </CommandGroup>+ </CommandList>+ </Command>+ </PopoverContent>+ </Popover>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/connect-element.tsx b/apps/desktop/src/app/capabilities/connectors/connect-element.tsxnew file mode 100644index 00000000000..1fa197b220f--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/connect-element.tsx@@ -0,0 +1,49 @@+import { useEffect } from 'react'++import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'+import { Loader2 } from '@/lib/icons'++import { type AccountOperation, syncAccountOperation } from './data/account-operations'++export interface ConnectElementProps {+ operation: AccountOperation+ onStopWaiting: () => void+}++export function ConnectElement({ operation, onStopWaiting }: ConnectElementProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage+ const link = operation.targets.find(target => target.connectUrl)?.connectUrl ?? null++ useEffect(() => {+ if (link === null && !operation.settled) {+ void syncAccountOperation(operation.opId)+ }+ }, [link, operation.opId, operation.settled])++ if (operation.settled) {+ return <p className="text-[0.78rem] text-(--ui-text-primary)">{copy.dialog.connectEnded}</p>+ }++ return (+ <div className="grid justify-items-start gap-2">+ <p className="flex items-center gap-2 text-[0.78rem] text-(--ui-text-primary)">+ <Loader2 aria-hidden className="size-3.5 shrink-0 animate-spin text-primary motion-reduce:animate-none" />+ {copy.card.reason.finishSignIn}+ </p>++ <div className="flex flex-wrap items-center gap-2">+ {link ? (+ <Button onClick={() => void window.hermesDesktop?.openExternal?.(link)} size="xs" variant="secondary">+ {copy.dialog.connectOpenAgain}+ </Button>+ ) : null}++ <Button onClick={onStopWaiting} size="xs" variant="text">+ {copy.card.verb.stopWaiting}+ </Button>+ </div>+ </div>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/connector-dialog.tsx b/apps/desktop/src/app/capabilities/connectors/connector-dialog.tsxnew file mode 100644index 00000000000..9e93fcb81d2--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/connector-dialog.tsx@@ -0,0 +1,372 @@+import { type ReactNode, type RefObject, useRef } from 'react'++import { Badge } from '@/components/ui/badge'+import { Button } from '@/components/ui/button'+import { Codicon } from '@/components/ui/codicon'+import { ConnectorLogo } from '@/components/ui/connector-logo'+import { Dialog, DialogClose, DialogContent, DialogDescription, DialogTitle } from '@/components/ui/dialog'+import { Switch } from '@/components/ui/switch'+import { useI18n } from '@/i18n'+import { connectorIconUrl } from '@/lib/connector-tools'+import { X } from '@/lib/icons'+import { cn } from '@/lib/utils'++import { CatalogMark } from './catalog-mark'+import { connectorKindWord, showsCatalogMark } from './connector-kind'+import { type InstallField, LocalInstall, LocalServerControl } from './local-server-control'+import type { ConnectorCardModel, ConnectorState, ConnectorVerb, ConnectorWayHosted } from './types'+import { WaysSection } from './ways-section'++type BadgeVariant = 'default' | 'destructive' | 'muted' | 'success' | 'warn'++const STATE_BADGE = {+ available: 'muted',+ broken: 'destructive',+ connected: 'success',+ connecting: 'warn',+ expired: 'warn',+ off: 'muted',+ unknown: 'muted'+} satisfies Record<ConnectorState, BadgeVariant>++const RULEABLE = {+ available: false,+ broken: false,+ connected: true,+ connecting: false,+ expired: false,+ off: true,+ unknown: true+} satisfies Record<ConnectorState, boolean>++const ruleable = (way: ConnectorWayHosted | null): boolean => way !== null && way.connected && RULEABLE[way.state]++export interface ConnectorDialogProps {+ advanced?: ReactNode+ card: ConnectorCardModel+ connectElement?: ReactNode+ cost?: { tokensPerCall?: string; usesPerMonth?: string }+ installFields?: readonly InstallField[]+ installing?: boolean+ menu?: ReactNode+ onAuthenticate?: () => void+ onConnect?: () => void+ onDisconnect?: () => void+ onInstall?: (env: Record<string, string>) => void+ onOpenAdmin?: () => void+ onOpenChange: (open: boolean) => void+ onReconnect?: () => void+ onServerToggle?: (next: boolean) => void+ onToggleForMe?: (next: boolean) => void+ onVerb?: () => void+ open: boolean+ orgDisabledCount?: number+ rulesReadOnly?: boolean+ togglePending?: boolean+ tools: ReactNode+}++const localTarget = (card: ConnectorCardModel): string | undefined => card.ways.local?.target++export function ConnectorDialog({ card, onOpenChange, open, tools, ...rest }: ConnectorDialogProps) {+ const { t } = useI18n()+ const local = card.residency === 'local'+ const titleRef = useRef<HTMLHeadingElement>(null)++ return (+ <Dialog onOpenChange={onOpenChange} open={open}>+ <DialogContent+ bodyClassName="gap-0 overflow-hidden p-0"+ className="max-h-[85vh] max-w-2xl"+ onOpenAutoFocus={event => {+ event.preventDefault()+ titleRef.current?.focus()+ }}+ showCloseButton={false}+ >+ <Header card={card} titleRef={titleRef} {...rest} />++ <div className="flex min-h-0 flex-1 flex-col">+ {local ? <LocalLead card={card} {...rest} /> : <HostedLead card={card} {...rest} />}++ {tools}++ {local ? <LocalFoot card={card} {...rest} /> : <HostedFoot card={card} {...rest} />}+ </div>++ <span className="sr-only">{t.connectorsPage.title}</span>+ </DialogContent>+ </Dialog>+ )+}++type PartProps = Omit<ConnectorDialogProps, 'onOpenChange' | 'open' | 'tools'>++function Header({+ card,+ menu,+ onToggleForMe,+ rulesReadOnly = false,+ titleRef,+ togglePending = false+}: PartProps & { titleRef: RefObject<HTMLHeadingElement | null> }) {+ const { t } = useI18n()+ const copy = t.connectorsPage.card+ const local = card.residency === 'local'+ const hosted = card.ways.hosted+ const appSwitch = ruleable(hosted) && onToggleForMe !== undefined++ return (+ <header className="flex shrink-0 items-center gap-2.5 border-b border-(--ui-stroke-tertiary) px-5 py-3">+ <ConnectorLogo+ className="size-9 shrink-0 rounded-[9px]"+ connector={{ iconUrl: local ? undefined : connectorIconUrl(card.slug), name: card.slug, title: card.name }}+ />++ <div className="grid min-w-0 flex-1 gap-0.5">+ <div className="flex min-w-0 items-center gap-2">+ <DialogTitle className="truncate text-base font-semibold outline-none" ref={titleRef} tabIndex={-1}>+ {card.name}+ </DialogTitle>++ <span className="shrink-0 text-[0.6875rem] text-(--ui-text-tertiary)">{connectorKindWord(card, copy)}</span>++ {showsCatalogMark(card) ? <CatalogMark /> : null}++ <Badge className="shrink-0" size="xs" variant={STATE_BADGE[card.state]}>+ {copy.state[card.stateWord]}+ </Badge>+ </div>++ <DialogDescription className="truncate text-[0.72rem] text-(--ui-text-secondary)">+ {card.description ?? localTarget(card) ?? copy.state[card.stateWord]}+ </DialogDescription>+ </div>++ <div className="flex shrink-0 items-center gap-2">+ {appSwitch && hosted && onToggleForMe ? (+ <Switch+ aria-label={t.connectorsPage.dialog.appSwitch(card.name)}+ checked={hosted.state !== 'off'}+ disabled={card.offBy === 'org' || togglePending || rulesReadOnly}+ onCheckedChange={onToggleForMe}+ size="xs"+ />+ ) : null}++ {menu}++ <DialogClose asChild>+ <Button aria-label={t.common.close} size="icon-xs" variant="ghost">+ <X className="size-3" />+ </Button>+ </DialogClose>+ </div>+ </header>+ )+}++interface LeadVerb {+ run: () => void+ verb: ConnectorVerb+}++function leadVerb({+ appSwitch,+ card,+ hasElement,+ onVerb+}: {+ appSwitch: boolean+ card: ConnectorCardModel+ hasElement: boolean+ onVerb?: () => void+}): LeadVerb | undefined {+ const verb = card.verb++ if (hasElement || verb === undefined || onVerb === undefined || (verb === 'turnBackOn' && appSwitch)) {+ return undefined+ }++ return { run: onVerb, verb }+}++function HostedLead({+ card,+ connectElement,+ installFields,+ installing,+ onAuthenticate,+ onDisconnect,+ onInstall,+ onOpenAdmin,+ onServerToggle,+ onToggleForMe,+ onVerb,+ orgDisabledCount = 0+}: PartProps) {+ const { t } = useI18n()+ const hosted = card.ways.hosted+ const reason = card.reason ? (card.reason.text ?? t.connectorsPage.card.reason[card.reason.key]) : undefined+ const appSwitch = ruleable(hosted) && onToggleForMe !== undefined+ const offerVerb = leadVerb({ appSwitch, card, hasElement: connectElement !== undefined, onVerb })+ const showsReason = reason !== undefined && connectElement === undefined+ const paired = card.ways.local !== null++ if (!paired && connectElement === undefined && offerVerb === undefined && !showsReason && orgDisabledCount <= 0) {+ return null+ }++ return (+ <div className="grid shrink-0 gap-3 border-b border-(--ui-stroke-tertiary) px-3.5 py-3">+ {connectElement}++ {showsReason ? <p className="text-[0.72rem] text-(--ui-text-secondary)">{reason}</p> : null}++ {offerVerb === undefined ? null : (+ <Button className="self-start" onClick={offerVerb.run} size="sm">+ {t.connectorsPage.card.verb[offerVerb.verb]}+ </Button>+ )}++ <OrgNote count={orgDisabledCount} onOpenAdmin={onOpenAdmin} />++ <WaysSection+ card={card}+ hostedVerb={false}+ installFields={installFields}+ installing={installing}+ onAuthenticate={onAuthenticate}+ onDisconnect={onDisconnect}+ onInstall={onInstall}+ onServerToggle={onServerToggle}+ />+ </div>+ )+}++function HostedFoot({ card }: PartProps) {+ const { t } = useI18n()++ return card.ways.hosted ? <FootLine>{t.connectorsPage.dialog.nousLine}</FootLine> : null+}++function LocalLead({+ card,+ installFields,+ installing,+ onAuthenticate,+ onConnect,+ onInstall,+ onReconnect,+ onServerToggle+}: PartProps) {+ const local = card.ways.local++ if (!local || (card.plugin !== undefined && !card.ways.hosted)) {+ return null+ }++ return (+ <div className="shrink-0 border-b border-(--ui-stroke-tertiary) px-3.5 py-2.5">+ {card.ways.hosted ? (+ <WaysSection+ card={card}+ installFields={installFields}+ installing={installing}+ onAuthenticate={onAuthenticate}+ onConnect={onConnect}+ onInstall={onInstall}+ onReconnect={onReconnect}+ onServerToggle={card.plugin === undefined ? onServerToggle : undefined}+ />+ ) : local.installed === false && onInstall ? (+ <LocalInstall installFields={installFields} installing={installing} onInstall={onInstall} />+ ) : (+ <LocalServerControl+ name={card.name}+ onAuthenticate={onAuthenticate}+ onServerToggle={card.plugin === undefined ? onServerToggle : undefined}+ way={local}+ />+ )}+ </div>+ )+}++function LocalFoot({ advanced, cost }: PartProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage.dialog+ const metrics = cost && (cost.tokensPerCall || cost.usesPerMonth)++ if (!metrics && !advanced) {+ return null+ }++ return (+ <div className="grid shrink-0 gap-3 border-t border-(--ui-stroke-tertiary) px-3.5 py-2.5">+ {metrics ? (+ <div className="flex gap-6">+ <Metric label={copy.tokensPerCall} value={cost?.tokensPerCall} />+ <Metric label={copy.usesPerMonth} value={cost?.usesPerMonth} />+ </div>+ ) : null}++ {advanced ? (+ <details className="group grid gap-2">+ <summary className="flex cursor-pointer list-none items-center gap-1.5 text-xs font-medium text-(--ui-text-primary)">+ <Codicon+ className={cn('shrink-0 transition-transform duration-100 group-open:rotate-90')}+ name="chevron-right"+ size="0.75rem"+ />+ <span className="shrink-0">{copy.advanced}</span>+ <span className="min-w-0 truncate font-normal text-(--ui-text-quaternary)">{copy.advancedHint}</span>+ </summary>+ <div className="pt-2">{advanced}</div>+ </details>+ ) : null}+ </div>+ )+}++function FootLine({ children }: { children: string }) {+ return (+ <p className="shrink-0 border-t border-(--ui-stroke-tertiary) px-3.5 py-2 text-[0.7rem] text-(--ui-text-tertiary)">+ {children}+ </p>+ )+}++function OrgNote({ count, onOpenAdmin }: { count: number; onOpenAdmin?: () => void }) {+ const { t } = useI18n()+ const copy = t.connectorsPage.dialog++ if (count <= 0) {+ return null+ }++ return (+ <div className="grid gap-1 rounded-md bg-(--ui-orange)/8 p-2.5">+ <p className="text-[0.7rem] text-(--ui-text-secondary)">{copy.orgNote(count)}</p>+ {onOpenAdmin ? (+ <Button className="justify-self-start" onClick={onOpenAdmin} size="inline" variant="textStrong">+ {copy.orgLink}+ </Button>+ ) : null}+ </div>+ )+}++function Metric({ label, value }: { label: string; value?: string }) {+ if (!value) {+ return null+ }++ return (+ <div className="grid gap-0.5">+ <span className="text-sm font-semibold tabular-nums text-(--ui-text-primary)">{value}</span>+ <span className="text-[0.65rem] text-(--ui-text-quaternary)">{label}</span>+ </div>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/connector-kind.ts b/apps/desktop/src/app/capabilities/connectors/connector-kind.tsnew file mode 100644index 00000000000..b09059fd5ab--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/connector-kind.ts@@ -0,0 +1,19 @@+import type { Translations } from '@/i18n/types'++import type { ConnectorCardModel } from './types'++export function connectorKindWord(card: ConnectorCardModel, copy: Translations['connectorsPage']['card']): string {+ if (card.residency === 'hosted') {+ return copy.kindManaged+ }++ if (card.plugin) {+ return copy.kindPlugin(card.plugin)+ }++ return card.ways.local?.inCatalog === true ? copy.kindCatalog : copy.kindCustom+}++export function showsCatalogMark(card: ConnectorCardModel): boolean {+ return card.inCatalog && card.plugin === undefined+}diff --git a/apps/desktop/src/app/capabilities/connectors/connector-row-card.tsx b/apps/desktop/src/app/capabilities/connectors/connector-row-card.tsxnew file mode 100644index 00000000000..d680916b0f0--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/connector-row-card.tsx@@ -0,0 +1,198 @@+import { Badge } from '@/components/ui/badge'+import { Button } from '@/components/ui/button'+import { ConnectorLogo } from '@/components/ui/connector-logo'+import { Switch } from '@/components/ui/switch'+import { useI18n } from '@/i18n'+import type { Translations } from '@/i18n/types'+import { connectorIconUrl } from '@/lib/connector-tools'+import { cn } from '@/lib/utils'++import { CatalogMark } from './catalog-mark'+import { connectorKindWord, showsCatalogMark } from './connector-kind'+import { twinPillOf } from './derive'+import type { ConnectorCardModel, ConnectorFact, ConnectorState } from './types'++const STATE_DOT = {+ available: 'bg-(--ui-text-quaternary)',+ broken: 'bg-(--ui-red)',+ connected: 'bg-(--ui-green)',+ connecting: 'bg-(--ui-yellow)',+ expired: 'bg-(--ui-orange)',+ off: 'bg-(--ui-text-quaternary)',+ unknown: 'bg-(--ui-text-quaternary)'+} satisfies Record<ConnectorState, string>++const REASON_TONE = {+ available: '',+ broken: 'text-(--ui-red)',+ connected: '',+ connecting: 'text-(--ui-text-secondary)',+ expired: 'text-(--ui-orange)',+ off: '',+ unknown: ''+} satisfies Record<ConnectorState, string>++function factText(copy: Translations['connectorsPage']['card'], fact: ConnectorFact): string {+ switch (fact.key) {+ case 'tools':+ return copy.fact.tools(fact.count)++ case 'toolsOff':+ return copy.fact.toolsOff(fact.count)++ case 'toolsOn':+ return copy.fact.toolsOn(fact.count)++ default:+ return copy.fact.toolsSomeOn(fact.count, fact.on ?? 0)+ }+}++export interface ConnectorRowCardProps {+ busy?: boolean+ card: ConnectorCardModel+ onOpen: () => void+ onPrefetch?: () => void+ onServerToggle?: (next: boolean) => void+ onVerb?: () => void+ selected?: boolean+}++export function ConnectorRowCard({+ busy = false,+ card,+ onOpen,+ onPrefetch,+ onServerToggle,+ onVerb,+ selected = false+}: ConnectorRowCardProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage.card+ const local = card.residency === 'local'+ const unset = card.state === 'available'++ const stateLabel = local && card.fact ? factText(copy, card.fact) : copy.state[card.stateWord]++ const reason = card.reason ? (card.reason.text ?? copy.reason[card.reason.key]) : undefined+ const twin = twinPillOf(card)++ return (+ <div+ className={cn(+ 'relative flex items-center gap-3 rounded-lg border p-3 transition-colors duration-100',+ selected+ ? 'border-(--theme-primary) bg-(--ui-row-active-background)'+ : 'border-(--ui-stroke-quaternary) bg-(--ui-bg-elevated) hover:bg-(--chrome-action-hover)'+ )}+ data-connector={card.slug}+ data-slot="connector-row-card"+ onFocus={onPrefetch}+ onPointerEnter={onPrefetch}+ >+ <ConnectorLogo+ className="size-9 shrink-0 rounded-[9px]"+ connector={{ iconUrl: local ? undefined : connectorIconUrl(card.slug), name: card.slug, title: card.name }}+ />++ <div className="grid min-w-0 flex-1 gap-0.5">+ <div className="flex min-w-0 flex-wrap items-center gap-x-1.5 gap-y-0.5">+ <button+ className="min-w-0 truncate text-[0.8125rem] font-semibold text-(--ui-text-primary) outline-none after:absolute after:inset-0 after:rounded-lg focus-visible:after:ring-[0.1875rem] focus-visible:after:ring-ring/50"+ onClick={onOpen}+ type="button"+ >+ {card.name}+ <span className="sr-only">{` — ${copy.open(card.name)}`}</span>+ </button>++ <span className="shrink-0 text-[0.6875rem] text-(--ui-text-tertiary)">{connectorKindWord(card, copy)}</span>++ {showsCatalogMark(card) ? <CatalogMark /> : null}++ {twin ? (+ <Badge className="shrink-0" size="xs" variant="muted">+ {twin === 'hostedTwin' ? copy.hostedTwin : copy.alsoLocal}+ </Badge>+ ) : null}+ </div>++ <SecondLine card={card} reason={reason} />+ </div>++ <CardLane+ busy={busy}+ card={card}+ onServerToggle={local && card.plugin === undefined ? onServerToggle : undefined}+ onVerb={onVerb}+ stateLabel={stateLabel}+ withDot={!unset}+ />+ </div>+ )+}++function CardLane({+ busy,+ card,+ onServerToggle,+ onVerb,+ stateLabel,+ withDot+}: {+ busy: boolean+ card: ConnectorCardModel+ onServerToggle?: (next: boolean) => void+ onVerb?: () => void+ stateLabel: string+ withDot: boolean+}) {+ const { t } = useI18n()+ const copy = t.connectorsPage.card+ const server = card.ways.local+ const fact = card.residency === 'hosted' && card.fact ? factText(copy, card.fact) : null++ return (+ <div className="relative z-10 flex w-[7.75rem] shrink-0 flex-col items-end gap-1">+ <span className="flex items-center gap-1.5 text-[0.6875rem] text-(--ui-text-secondary)">+ {withDot ? <span aria-hidden className={cn('size-[5px] shrink-0 rounded-full', STATE_DOT[card.state])} /> : null}+ <span className="truncate">{stateLabel}</span>+ </span>++ {server?.installed === true && onServerToggle ? (+ <Switch+ aria-label={server.serverEnabled ? copy.turnServerOff(card.name) : copy.turnServerOn(card.name)}+ checked={server.serverEnabled ?? false}+ onCheckedChange={onServerToggle}+ size="xs"+ />+ ) : null}++ {card.verb && onVerb ? (+ <Button+ disabled={busy}+ loading={busy}+ onClick={onVerb}+ size="xs"+ variant={card.state === 'available' ? 'outline' : 'secondary'}+ >+ {copy.verb[card.verb]}+ </Button>+ ) : null}++ {card.verb === undefined && fact !== null ? (+ <span className="truncate text-[0.6875rem] text-(--ui-text-tertiary)">{fact}</span>+ ) : null}+ </div>+ )+}++function SecondLine({ card, reason }: { card: ConnectorCardModel; reason?: string }) {+ if (reason) {+ return <p className={cn('truncate text-[0.72rem]', REASON_TONE[card.state])}>{reason}</p>+ }++ return card.description ? (+ <p className="line-clamp-2 text-[0.72rem] leading-snug text-(--ui-text-secondary)">{card.description}</p>+ ) : null+}diff --git a/apps/desktop/src/app/capabilities/connectors/connectors-directory.tsx b/apps/desktop/src/app/capabilities/connectors/connectors-directory.tsxnew file mode 100644index 00000000000..73556b0b55c--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/connectors-directory.tsx@@ -0,0 +1,225 @@+import { type ReactNode } from 'react'++import { PanelEmpty } from '@/app/overlays/panel'+import { Button } from '@/components/ui/button'+import { ErrorBanner } from '@/components/ui/error-state'+import { SearchField } from '@/components/ui/search-field'+import { SegmentedControl } from '@/components/ui/segmented-control'+import { useI18n } from '@/i18n'++import { ConnectorRowCard } from './connector-row-card'+import { cardKey, EMPTY_CONNECTORS_FILTER } from './derive'+import { derivePage, showsAttentionFirst } from './derive-page'+import { ToolsWash } from './tools-status'+import type { ConnectorCardModel, ConnectorGroupModel, ConnectorSegmentId, ConnectorsFilter } from './types'+++export interface ConnectorsDirectoryProps {+ addYourOwn?: ReactNode+ busyKey?: null | string+ cards: ConnectorCardModel[]+ filter: ConnectorsFilter+ hostedFailed?: boolean+ loading?: boolean+ notices?: ReactNode+ onFilterChange: (next: ConnectorsFilter) => void+ onOpen: (card: ConnectorCardModel) => void+ onPrefetch?: (card: ConnectorCardModel) => void+ onRetryHosted?: () => void+ onServerToggle?: (card: ConnectorCardModel, next: boolean) => void+ onVerb?: (card: ConnectorCardModel) => void+ selectedKey?: null | string+}++export function ConnectorsDirectory({+ addYourOwn,+ busyKey = null,+ cards,+ filter,+ hostedFailed = false,+ loading = false,+ notices,+ onFilterChange,+ onOpen,+ onPrefetch,+ onRetryHosted,+ onServerToggle,+ onVerb,+ selectedKey = null+}: ConnectorsDirectoryProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage+ const where = copy.residencyLocal+ const segmentLabel = (id: ConnectorSegmentId) => (id === 'local' ? where : copy.segment[id])+ const set = (patch: Partial<ConnectorsFilter>) => onFilterChange({ ...filter, ...patch })++ const { groups, hiddenMatches, segment, segments } = derivePage(cards, filter)++ const showSegments = segments.length > 2+ const segmentFellBack = segments.length > 0 && segment !== filter.segment+++ return (+ <div className="flex min-h-0 flex-1 flex-col gap-3" data-slot="connectors-directory">+ <div className="flex shrink-0 items-center gap-3">+ <h2 className="flex-1 text-sm font-semibold text-(--ui-text-primary)">{copy.title}</h2>+ {addYourOwn}+ </div>++ {cards.length === 0 ? null : (+ <>+ <div className="flex shrink-0 items-center gap-3 border-b border-(--ui-stroke-tertiary) pb-1.5">+ <SearchField+ containerClassName="min-w-0 flex-1"+ onChange={query => set({ query })}+ placeholder={copy.searchPlaceholder(cards.length)}+ value={filter.query}+ />+ </div>++ {showSegments || segmentFellBack || hiddenMatches > 0 ? (+ <div className="flex shrink-0 flex-wrap items-center gap-2">+ {showSegments ? (+ <SegmentedControl+ onChange={(next: ConnectorSegmentId) => set({ segment: next })}+ options={segments.map(option => ({+ id: option.id,+ label: `${segmentLabel(option.id)} ${option.count}`+ }))}+ value={segment}+ />+ ) : null}++ {segmentFellBack ? (+ <span className="text-[0.7rem] text-(--ui-text-tertiary)">+ {copy.page.segmentNoMatch(segmentLabel(filter.segment))}+ </span>+ ) : null}++ {hiddenMatches > 0 ? (+ <span className="flex items-center gap-1 text-[0.7rem] text-(--ui-text-tertiary)">+ {copy.page.matchesElsewhere(hiddenMatches)}+ <Button onClick={() => set({ segment: 'all' })} size="xs" variant="text">+ {copy.page.showAllMatches}+ </Button>+ </span>+ ) : null}+ </div>+ ) : null}+ </>+ )}++ {notices}++ {hostedFailed && onRetryHosted ? (+ <ErrorBanner className="shrink-0 items-center">+ <span className="flex flex-wrap items-center gap-x-1.5 gap-y-1">+ <span className="font-medium">{copy.page.hostedFailedTitle}</span>+ <span className="opacity-80">{copy.page.hostedFailedBody}</span>+ <Button className="text-destructive" onClick={onRetryHosted} size="xs" variant="text">+ {copy.page.retry}+ </Button>+ </span>+ </ErrorBanner>+ ) : null}++ {loading ? (+ <ToolsWash label={copy.page.loading} rows={10} />+ ) : groups.length > 0 ? (+ <div className="grid min-h-0 flex-1 content-start gap-6 overflow-y-auto overscroll-contain pb-4">+ {groups.map(group => (+ <Group+ busyKey={busyKey}+ group={group}+ key={group.id}+ onOpen={onOpen}+ onPrefetch={onPrefetch}+ onServerToggle={onServerToggle}+ onVerb={onVerb}+ selectedKey={selectedKey}+ where={where}+ />+ ))}+ </div>+ ) : cards.length === 0 ? (+ hostedFailed ? null : (+ <PanelEmpty action={addYourOwn} icon="plug" title={copy.page.emptyTitle} />+ )+ ) : (+ <PanelEmpty+ action={+ <div className="flex items-center gap-2">+ <Button onClick={() => set(EMPTY_CONNECTORS_FILTER)} size="xs" variant="secondary">+ {copy.page.clearSearch}+ </Button>+ {addYourOwn}+ </div>+ }+ description={copy.page.noMatchBody}+ icon="search"+ title={copy.page.noMatchTitle}+ />+ )}+ </div>+ )+}++function Group({+ busyKey,+ group,+ onOpen,+ onPrefetch,+ onServerToggle,+ onVerb,+ selectedKey,+ where+}: {+ busyKey: null | string+ group: ConnectorGroupModel+ onOpen: (card: ConnectorCardModel) => void+ onPrefetch?: (card: ConnectorCardModel) => void+ onServerToggle?: (card: ConnectorCardModel, next: boolean) => void+ onVerb?: (card: ConnectorCardModel) => void+ selectedKey: null | string+ where: string+}) {+ const { t } = useI18n()+ const copy = t.connectorsPage.group++ return (+ <section className="grid gap-2">+ <header className="flex items-center gap-2">+ <h3 className="text-xs font-semibold text-(--ui-text-primary)">+ {group.id === 'local' ? where : copy[group.id]}+ </h3>+ <span className="tabular-nums text-xs text-(--ui-text-tertiary)">{group.cards.length}</span>++ {group.id === 'connected' && showsAttentionFirst(group) ? <Note>{copy.connectedNote}</Note> : null}+ {group.id === 'off' ? <Note>{copy.offNote}</Note> : null}+ </header>++ <div className="grid gap-3 sm:grid-cols-2">+ {group.cards.map(card => {+ const key = cardKey(card)++ return (+ <ConnectorRowCard+ busy={busyKey === key}+ card={card}+ key={key}+ onOpen={() => onOpen(card)}+ onPrefetch={onPrefetch ? () => onPrefetch(card) : undefined}+ onServerToggle={onServerToggle ? next => onServerToggle(card, next) : undefined}+ onVerb={onVerb ? () => onVerb(card) : undefined}+ selected={selectedKey === key}+ />+ )+ })}+ </div>+ </section>+ )+}++function Note({ children }: { children: ReactNode }) {+ return <span className="truncate text-[0.65rem] text-(--ui-text-tertiary)">{children}</span>+}diff --git a/apps/desktop/src/app/capabilities/connectors/connectors-tab.tsx b/apps/desktop/src/app/capabilities/connectors/connectors-tab.tsxnew file mode 100644index 00000000000..d8d13f4531e--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/connectors-tab.tsx@@ -0,0 +1,388 @@+import { useStore } from '@nanostores/react'+import { useEffect, useMemo, useState } from 'react'+import { useLocation, useNavigate } from 'react-router'++import { Button } from '@/components/ui/button'+import { ConfirmDialog } from '@/components/ui/confirm-dialog'+import type { HermesGateway, ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'+import { $freeTierStatus } from '@/store/free-tier'+import { openFreeTierSignIn } from '@/store/free-tier-sign-in'+import { notifyError, readableError } from '@/store/notifications'++import { installBundledEntry } from '../mcp/install-catalog-entry'+import { useMcpServers } from '../mcp/use-mcp-servers'++import { AddServerDialog } from './add-dialog'+import { ConnectorsDirectory } from './connectors-directory'+import { $abandonedConnects, $accountOperations, abandonConnect, accountOperationFor } from './data/account-operations'+import { joinBundledEntries, joinLocalServers, pickAccount } from './data/join'+import { useConnectConnector, useConnectorSwitch, useDisconnectAccount } from './data/mutations'+import { seedLocalServers, startConnectorPersistence, storeLocalServers } from './data/persist'+import { prefetchConnectorTools, usePrefetchConnectedTools } from './data/prefetch'+import { useHostedConnectors, usePluginServers } from './data/queries'+import {+ cardKey,+ deriveCards,+ EMPTY_CONNECTORS_FILTER,+ forgetAbandoned,+ hostedCardKey,+ localServerName+} from './derive'+import { HostedConnectorDialog } from './hosted-dialog'+import { LocalConnectorDialog } from './local-dialog'+import { RemoveServerConfirm } from './local-slots'+import { openToolsList, resetOpenedTools } from './tools-summary'+import type { ConnectorCardModel, ConnectorsFilter, HostedPhase } from './types'++const toolsListKey = (card: ConnectorCardModel) => (card.residency === 'local' ? localServerName(card) : card.slug)++export interface ConnectorsTabProps {+ gateway: HermesGateway | null+ profile: ProfileScope+}++export function ConnectorsTab({ gateway, profile }: ConnectorsTabProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage++ const hosted = useHostedConnectors(profile)+ const mcp = useMcpServers({ gateway, profile })+ const operations = useStore($accountOperations)+ const abandoned = useStore($abandonedConnects)+ const freeTier = useStore($freeTierStatus)++ const connector = useConnectConnector(profile)+ const switcher = useConnectorSwitch(profile)+ const remover = useDisconnectAccount(profile)++ const [filter, setFilter] = useState<ConnectorsFilter>(EMPTY_CONNECTORS_FILTER)+ const [openKey, setOpenKey] = useState<null | string>(null)+ const [addOpen, setAddOpen] = useState(false)+ const [removeServer, setRemoveServer] = useState<null | ConnectorCardModel>(null)+ const [disconnecting, setDisconnecting] = useState<null | ConnectorCardModel>(null)+ const [installing, setInstalling] = useState<null | string>(null)++ const local = useMemo(+ () =>+ joinLocalServers({+ catalog: mcp.catalog,+ servers: mcp.servers,+ status: mcp.statuses,+ toolCounts: mcp.toolCounts,+ usage: mcp.usageByServer+ }),+ [mcp.catalog, mcp.servers, mcp.statuses, mcp.toolCounts, mcp.usageByServer]+ )++ const bundled = useMemo(() => joinBundledEntries(mcp.availableCatalog), [mcp.availableCatalog])++ const lastKnownServers = useMemo(() => seedLocalServers(profile), [profile])+ const pluginServers = usePluginServers(profile)++ const servers = useMemo(+ () => [...(mcp.configLoading ? lastKnownServers : local), ...pluginServers],+ [lastKnownServers, local, mcp.configLoading, pluginServers]+ )++ useEffect(() => {+ if (!mcp.configLoading) {+ storeLocalServers(profile, local)+ }+ }, [local, mcp.configLoading, profile])++ const cards = useMemo(+ () =>+ deriveCards({+ bundled,+ hosted: forgetAbandoned(hosted.rows, new Set(abandoned)),+ local: servers,+ titles: hosted.titles+ }),+ [abandoned, bundled, hosted.rows, hosted.titles, servers]+ )++ useEffect(startConnectorPersistence, [])++ useEffect(() => {+ resetOpenedTools()+ $abandonedConnects.set([])+ }, [profile])++ usePrefetchConnectedTools(profile, cards)++ const openCard = useMemo(() => cards.find(card => cardKey(card) === openKey) ?? null, [cards, openKey])++ useOpenFromRoute(cards, setOpenKey)++ const write = async (pending: Promise<{ error?: unknown; ok: boolean }>) => {+ const outcome = await pending++ if (!outcome.ok) {+ notifyError(outcome.error, copy.page.writeFailed)+ }+ }++ const startConnect = async (card: ConnectorCardModel, reconnect: boolean) => {+ const outcome = await connector.connect(card.slug, { reconnect })++ if (!outcome.ok) {+ notifyError(outcome.error, t.connectors.connectErrorFor(card.name))++ return+ }++ const url = outcome.operation.targets.find(target => target.connectUrl)?.connectUrl++ if (url) {+ void window.hermesDesktop?.openExternal?.(url)+ }++ setOpenKey(cardKey(card))+ }++ const bundledEntry = (card: ConnectorCardModel) =>+ mcp.availableCatalog.find(candidate => candidate.name === card.ways.local?.entryName) ?? null++ const startInstall = async (card: ConnectorCardModel, env: Record<string, string>) => {+ const entry = bundledEntry(card)++ if (!entry) {+ return+ }++ setInstalling(cardKey(card))++ try {+ await installBundledEntry(entry, env, profile)+ await mcp.onCatalogInstalled()+ setOpenKey(cardKey(card))+ } catch (error) {+ notifyError(error, t.settings.mcp.catalogInstallFailed(card.name))+ } finally {+ setInstalling(null)+ }+ }++ const runVerb = (card: ConnectorCardModel) => {+ const open = accountOperationFor(operations, card.slug)++ switch (card.verb) {+ case 'authenticate':+ void mcp.authenticate(localServerName(card))++ return++ case 'connect':+ void startConnect(card, false)++ return++ case 'install':+ if (card.ways.local?.entryName && card.ways.local.needsEnv !== true) {+ void startInstall(card, {})++ return+ }++ break++ case 'reconnect':++ case 'tryAgain':+ void startConnect(card, true)++ return+ case 'stopWaiting': {+ if (open) {+ void write(connector.giveUp(open.opId))++ return+ }++ abandonConnect([card.slug])++ const pending = pickAccount(hosted.accounts, card.slug)++ if (pending) {+ void write(remover.disconnect(pending.connection_id))+ }++ return+ }++ case 'turnBackOn':+ void write(switcher.setEnabled(card.slug, true))++ return++ default:+ break+ }++ setOpenKey(cardKey(card))+ }++ const busySlug = switcher.pending ?? connector.pending+ const busyKey = installing ?? (busySlug === null ? null : hostedCardKey(busySlug))++ return (+ <div className="flex h-full min-h-0 flex-col gap-3 px-4 pb-2">+ <ConnectorsDirectory+ addYourOwn={+ <Button disabled={mcp.profilePending} onClick={() => setAddOpen(true)} size="xs" variant="outline">+ {copy.add.action}+ </Button>+ }+ busyKey={busyKey}+ cards={cards}+ filter={filter}+ hostedFailed={hosted.phase === 'failed'}+ loading={(hosted.phase === 'loading' || mcp.configLoading || mcp.catalogLoading) && cards.length === 0}+ notices={<HostedNotice hasGuest={freeTier?.has_guest === true} phase={hosted.phase} />}+ onFilterChange={setFilter}+ onOpen={card => setOpenKey(cardKey(card))}+ onPrefetch={card => {+ if (card.ways.hosted) {+ prefetchConnectorTools(profile, card.slug)+ }+ }}+ onRetryHosted={hosted.refetch}+ onServerToggle={(card, next) => {+ if (card.plugin === undefined) {+ void mcp.setServerEnabled(localServerName(card), next)+ }+ }}+ onVerb={runVerb}+ selectedKey={openKey}+ />++ {openCard?.residency === 'local' ? (+ <LocalConnectorDialog+ card={openCard}+ controller={mcp}+ installFields={bundledEntry(openCard)?.required_env}+ installing={installing === cardKey(openCard)}+ onClose={() => setOpenKey(null)}+ onConnect={() => void startConnect(openCard, false)}+ onInstall={env => void startInstall(openCard, env)}+ onReconnect={() => void startConnect(openCard, true)}+ onRemoveServer={() => setRemoveServer(openCard)}+ profile={profile}+ />+ ) : null}++ {openCard?.residency === 'hosted' ? (+ <HostedConnectorDialog+ card={openCard}+ controller={mcp}+ hosted={hosted}+ installFields={bundledEntry(openCard)?.required_env}+ installing={installing === cardKey(openCard)}+ onClose={() => setOpenKey(null)}+ onConnect={() => void startConnect(openCard, false)}+ onDisconnect={() => setDisconnecting(openCard)}+ onGiveUp={opId => void write(connector.giveUp(opId))}+ onInstall={env => void startInstall(openCard, env)}+ onReconnect={() => void startConnect(openCard, true)}+ onRemoveServer={() => setRemoveServer(openCard)}+ onToggleForMe={next => void write(switcher.setEnabled(openCard.slug, next))}+ onVerb={() => runVerb(openCard)}+ profile={profile}+ togglePending={switcher.pending === openCard.slug}+ />+ ) : null}++ <AddServerDialog controller={mcp} onOpenChange={setAddOpen} open={addOpen} profile={profile} />++ <RemoveServerConfirm+ card={removeServer}+ controller={mcp}+ onClose={() => setRemoveServer(null)}+ onRemoved={() => setOpenKey(null)}+ />++ <ConfirmDialog+ confirmLabel={copy.dialog.disconnect}+ description={copy.dialog.disconnectBody}+ destructive+ onClose={() => setDisconnecting(null)}+ onConfirm={async () => {+ const card = disconnecting+ const account = card ? pickAccount(hosted.accounts, card.slug) : null++ if (!account) {+ throw new Error(copy.page.disconnectNoAccount)+ }++ const outcome = await remover.disconnect(account.connection_id)++ if (!outcome.ok) {+ throw new Error(readableError(outcome.error, copy.page.writeFailed).message)+ }++ setOpenKey(null)+ }}+ open={disconnecting !== null}+ title={copy.dialog.disconnectTitle(disconnecting?.name ?? '')}+ />+ </div>+ )+}++function HostedNotice({ hasGuest, phase }: { hasGuest: boolean; phase: HostedPhase }) {+ const { t } = useI18n()+ const copy = t.connectorsPage.page++ if (phase === 'signedOut') {+ return (+ <p className="flex shrink-0 items-center gap-1 text-[0.7rem] text-(--ui-text-tertiary)">+ {copy.signInLine}+ <Button onClick={() => openFreeTierSignIn()} size="xs" variant="text">+ {copy.signIn}+ </Button>+ </p>+ )+ }++ if (phase === 'unavailable') {+ return <p className="shrink-0 text-[0.7rem] text-(--ui-text-tertiary)">{copy.managedUnavailable}</p>+ }++ return hasGuest ? <p className="shrink-0 text-[0.7rem] text-(--ui-text-tertiary)">{copy.freeTierNote}</p> : null+}++function useOpenFromRoute(cards: readonly ConnectorCardModel[], open: (key: string) => void): void {+ const { hash, pathname, search } = useLocation()+ const navigate = useNavigate()++ useEffect(() => {+ const params = new URLSearchParams(search)+ const server = params.get('server')+ const slug = params.get('connector')++ if (!server && !slug) {+ return+ }++ const target = server+ ? cards.find(card => card.residency === 'local' && card.slug === server)+ : cards.find(card => card.slug === slug)++ if (!target) {+ return+ }++ if (params.get('tool')) {+ openToolsList(toolsListKey(target))+ }++ open(cardKey(target))+ params.delete('server')+ params.delete('connector')+ params.delete('tool')++ const query = params.toString()+ navigate({ hash, pathname, search: query ? `?${query}` : '' }, { replace: true })+ }, [cards, hash, navigate, open, pathname, search])+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/account-operations.ts b/apps/desktop/src/app/capabilities/connectors/data/account-operations.tsnew file mode 100644index 00000000000..dbf970b1f77--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/account-operations.ts@@ -0,0 +1,167 @@+import type {+ ConnectionOperationStatus,+ ConnectionSettleReason,+ ConnectionUpdatePayload,+ ConnectorsConnectResult+} from '@hermes/shared'+import { atom } from 'nanostores'++import type { ProfileScope } from '@/hermes'+import { type ConnectionTarget, parseConnectionTarget } from '@/store/connection-request'++import { invalidateConnectors } from './keys'+import { accountOperationStatus } from './rpc'++export interface AccountOperation {+ connectors: string[]+ deadlineAt: number+ opId: string+ scope: ProfileScope+ seq: number+ settled: boolean+ settledBy: ConnectionSettleReason | null+ targets: ConnectionTarget[]+}++export const $accountOperations = atom<Readonly<Record<string, AccountOperation>>>({})++export const $abandonedConnects = atom<readonly string[]>([])++export function abandonConnect(slugs: readonly string[]): void {+ const kept = $abandonedConnects.get().filter(slug => !slugs.includes(slug))++ $abandonedConnects.set([...kept, ...slugs])+}++function resumeConnect(slugs: readonly string[]): void {+ const next = $abandonedConnects.get().filter(slug => !slugs.includes(slug))++ if (next.length !== $abandonedConnects.get().length) {+ $abandonedConnects.set(next)+ }+}++const parseTargets = (targets: ConnectionUpdatePayload['targets']): ConnectionTarget[] =>+ targets.map(parseConnectionTarget).filter((target): target is ConnectionTarget => target !== null)++export function accountOperationFor(+ operations: Readonly<Record<string, AccountOperation>>,+ slug: string+): AccountOperation | null {+ const mine = Object.values(operations).filter(operation => operation.connectors.includes(slug))++ return mine.find(operation => !operation.settled) ?? mine[mine.length - 1] ?? null+}++export function startAccountOperation(+ scope: ProfileScope,+ connectors: readonly string[],+ snapshot: ConnectorsConnectResult+): AccountOperation {+ const operation: AccountOperation = {+ connectors: [...connectors],+ deadlineAt: snapshot.deadline_at,+ opId: snapshot.op_id,+ scope,+ seq: snapshot.seq,+ settled: snapshot.settled,+ settledBy: snapshot.settled_by ?? null,+ targets: parseTargets(snapshot.targets)+ }++ resumeConnect(operation.connectors)++ const kept = Object.entries($accountOperations.get()).filter(+ ([, previous]) => !previous.settled || !previous.connectors.some(slug => operation.connectors.includes(slug))+ )++ $accountOperations.set({ ...Object.fromEntries(kept), [operation.opId]: operation })+ refetchOnSettle(operation)++ return operation+}++function carryLink(held: ConnectionTarget | undefined, target: ConnectionTarget): ConnectionTarget {+ if (!held) {+ return target+ }++ const reissued = target.state === 'initiated' && held.state !== 'initiated'++ return {+ ...target,+ connectUrl: target.connectUrl ?? (reissued ? null : held.connectUrl),+ connectionId: target.connectionId || held.connectionId+ }+}++type SnapshotSource = 'broadcast' | 'reply'++function applySnapshot(+ opId: string,+ snapshot: Pick<ConnectionOperationStatus, 'deadline_at' | 'seq' | 'settled' | 'settled_by' | 'targets'>,+ source: SnapshotSource+): void {+ const current = $accountOperations.get()[opId]++ if (!current || (source === 'broadcast' ? snapshot.seq <= current.seq : snapshot.seq < current.seq)) {+ return+ }++ const held = new Map(current.targets.map(target => [target.name, target] as const))++ const next: AccountOperation = {+ ...current,+ deadlineAt: snapshot.deadline_at,+ seq: snapshot.seq,+ settled: snapshot.settled,+ settledBy: snapshot.settled_by ?? null,+ targets: parseTargets(snapshot.targets).map(target => carryLink(held.get(target.name), target))+ }++ $accountOperations.set({ ...$accountOperations.get(), [next.opId]: next })+ refetchOnSettle(next)+}++export function applyAccountConnectionUpdate(payload: ConnectionUpdatePayload): void {+ if (payload.owner.type !== 'account') {+ return+ }++ applySnapshot(payload.op_id, payload, 'broadcast')+}++export async function syncAccountOperation(opId: string): Promise<void> {+ const operation = $accountOperations.get()[opId]++ if (!operation) {+ return+ }++ try {+ const status = await accountOperationStatus(operation.scope, opId)+ applySnapshot(opId, status, 'reply')+ // eslint-disable-next-line no-empty+ } catch {+ }+}++export function clearAccountOperation(opId: string): void {+ const operations = $accountOperations.get()++ if (!(opId in operations)) {+ return+ }++ const next = { ...operations }+ delete next[opId]+ $accountOperations.set(next)+}++function refetchOnSettle(operation: AccountOperation): void {+ if (!operation.settled) {+ return+ }++ invalidateConnectors(operation.scope, 'list', 'accounts')+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/deep-link.ts b/apps/desktop/src/app/capabilities/connectors/data/deep-link.tsnew file mode 100644index 00000000000..4c0fea1fcfb--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/deep-link.ts@@ -0,0 +1,29 @@+import { CAPABILITIES_ROUTE } from '../../../routes'++import { $accountOperations } from './account-operations'+import { wakeAccountOperation } from './rpc'++const connectorRoute = (slug: string): string =>+ `${CAPABILITIES_ROUTE}?tab=connectors&connector=${encodeURIComponent(slug)}`++export async function resumeAccountConnect(opId: string, navigate: (to: string) => void): Promise<boolean> {+ const operation = $accountOperations.get()[opId]++ if (!operation) {+ return false+ }++ if (operation.settled) {+ return true+ }++ navigate(connectorRoute(operation.connectors[0] ?? ''))++ try {+ await wakeAccountOperation(operation.scope, opId)+ } catch {+ // The operation can settle and leave the live registry between the link and this RPC.+ }++ return true+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/join.ts b/apps/desktop/src/app/capabilities/connectors/data/join.tsnew file mode 100644index 00000000000..5d0183d4901--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/join.ts@@ -0,0 +1,309 @@+import type {+ ConnectorAccountRow,+ ConnectorCatalogRow,+ ConnectorRow as ConnectorListRow,+ ConnectorPolicyGetResult,+ ConnectorPolicyLayer,+ McpRuntimeStatus,+ McpServerRuntimeRow,+ McpServerSummary+} from '@hermes/shared'++import type { McpCatalogEntry } from '@/hermes'+import { connectorTitle } from '@/lib/connector-tools'+import type { McpServers } from '@/lib/mcp-servers'++import { canAuthenticate } from '../../mcp/mcp-status'+import { toolRows } from '../derive-tools'+import type {+ BundledEntryInput,+ ConnectorAuthType,+ HostedConnectorInput,+ LocalServerInput,+ LocalServerStatus,+ ToolInput,+ ToolRowModel+} from '../types'++export interface ConnectorPolicyTagRules {+ disable: readonly string[]+ enable: readonly string[]+}++export interface ConnectorPolicyRules {+ allowed: ReadonlySet<string> | null+ denied: ReadonlySet<string>+ revision: string+ tags: ConnectorPolicyTagRules+ tools: Readonly<Record<string, readonly string[]>>+}++export interface ConnectorPolicyView {+ member: ConnectorPolicyRules | null+ others: readonly ConnectorPolicyRules[]+}++export const EMPTY_POLICY: ConnectorPolicyView = { member: null, others: [] }++const NO_TAGS: ConnectorPolicyTagRules = { disable: [], enable: [] }++function rulesOf(layer: ConnectorPolicyLayer): ConnectorPolicyRules {+ const body = layer.body+ const base = { revision: layer.revision, tags: NO_TAGS, tools: {} }++ if (body.mode === 'unrestricted') {+ return { ...base, allowed: null, denied: new Set() }+ }++ if (body.mode === 'deny-all') {+ return { ...base, allowed: new Set(), denied: new Set() }+ }++ const tags: ConnectorPolicyTagRules = {+ disable: body.tags?.disable ?? [],+ enable: body.tags?.enable ?? []+ }++ return body.mode === 'allow'+ ? { allowed: new Set(body.connectors), denied: new Set(), revision: layer.revision, tags, tools: body.tools }+ : {+ allowed: null,+ denied: new Set(body.disabled_connectors),+ revision: layer.revision,+ tags,+ tools: body.tools+ }+}++export function readPolicy(result: ConnectorPolicyGetResult): ConnectorPolicyView {+ const layers = result.layers+ const member = layers.find(layer => layer.kind === 'member')++ return {+ member: member ? rulesOf(member) : null,+ others: layers.filter(layer => layer.kind !== 'member').map(rulesOf)+ }+}++const layerAllows = (rules: ConnectorPolicyRules, slug: string): boolean =>+ (rules.allowed === null || rules.allowed.has(slug)) && !rules.denied.has(slug)++export const memberEnables = (policy: ConnectorPolicyView, slug: string): boolean =>+ policy.member === null || layerAllows(policy.member, slug)++export const orgLocks = (policy: ConnectorPolicyView, slug: string): boolean =>+ policy.others.some(rules => !layerAllows(rules, slug))++export const memberDisabledTools = (policy: ConnectorPolicyView, slug: string): readonly string[] =>+ policy.member?.tools[slug] ?? []++export const memberRevision = (policy: ConnectorPolicyView): string | undefined => policy.member?.revision++export function orgLockedTools(policy: ConnectorPolicyView, slug: string, tools: readonly ToolInput[]): Set<string> {+ const locked = new Set<string>()++ for (const rules of policy.others) {+ for (const tool of rules.tools[slug] ?? []) {+ locked.add(tool)+ }++ for (const tool of tools) {+ const hints = new Set(tool.hints)+ const disabledByTag = rules.tags.disable.some(tag => hints.has(tag))+ const missingEveryEnabledTag = rules.tags.enable.length > 0 && !rules.tags.enable.some(tag => hints.has(tag))++ if (disabledByTag || missingEveryEnabledTag) {+ locked.add(tool.slug)+ }+ }+ }++ return locked+}++export function connectorToolRows(+ policy: ConnectorPolicyView,+ slug: string,+ tools: readonly ToolInput[]+): ToolRowModel[] {+ return toolRows(tools, new Set(memberDisabledTools(policy, slug)), orgLockedTools(policy, slug, tools))+}++export interface HostedJoinInput {+ accounts: readonly ConnectorAccountRow[]+ catalog: readonly ConnectorCatalogRow[]+ list: readonly ConnectorListRow[]+ policy: ConnectorPolicyView+ rulesReadable?: boolean+}++const text = (value: null | string | undefined): string | undefined =>+ value !== null && value !== undefined && value.trim() !== '' ? value : undefined++export function pickAccount(accounts: readonly ConnectorAccountRow[], slug: string): ConnectorAccountRow | undefined {+ const mine = accounts.filter(account => account.connector === slug)+ const rank = (account: ConnectorAccountRow) => (account.active ? 0 : 1)++ return [...mine].sort((a, b) => rank(a) - rank(b) || b.created_at.localeCompare(a.created_at))[0]+}++export function connectorTitles(input: Pick<HostedJoinInput, 'catalog' | 'list'>) {+ const titles: Record<string, string> = {}++ for (const slug of hostedSlugs(input)) {+ titles[slug] = text(input.catalog.find(row => row.slug === slug)?.name) ?? connectorTitle(slug)+ }++ return titles+}++function hostedSlugs({ catalog, list }: Pick<HostedJoinInput, 'catalog' | 'list'>): string[] {+ const slugs = new Set(catalog.map(row => row.slug))++ for (const row of list) {+ if (row.connector) {+ slugs.add(row.connector)+ }+ }++ return [...slugs]+}++export function joinHostedConnectors({+ accounts,+ catalog,+ list,+ policy,+ rulesReadable = true+}: HostedJoinInput): HostedConnectorInput[] {+ return hostedSlugs({ catalog, list }).map(slug => {+ const entry = catalog.find(row => row.slug === slug)+ const row = list.find(candidate => candidate.connector === slug)+ const account = pickAccount(accounts, slug)+ const off = rulesReadable ? memberDisabledTools(policy, slug) : (row?.gateway_disabled_tools ?? [])++ return {+ accountLabel: account?.label,+ connected: account !== undefined || row?.connected === true,+ connectedAt: account?.created_at,+ connectionStatus: account?.status ?? row?.connection_status ?? undefined,+ description: entry?.description,+ disabledTools: off,+ enabled: memberEnables(policy, slug) && row?.enabled !== false,+ inCatalog: entry !== undefined,+ orgLocked: orgLocks(policy, slug),+ slug,+ statusReason: text(account?.status_reason) ?? text(row?.status_reason),+ toolsOff: off.length > 0 ? off.length : undefined+ }+ })+}++export interface LocalJoinInput {+ catalog: readonly McpCatalogEntry[]+ servers: McpServers+ status: Readonly<Record<string, LocalServerStatus>>+ toolCounts?: Readonly<Record<string, { on: number; total: number }>>+ usage?: Readonly<Record<string, number>>+}++interface ServerEntry {+ args?: string[]+ command?: string+ url?: string+}++const targetOf = (entry: McpServers[string]): string => {+ // SAFETY: mcp.json is hand-written, so each field is read back as absent unless it is the string it claims.+ const { args, command, url } = entry as ServerEntry++ if (text(url) !== undefined) {+ return url ?? ''+ }++ const parts = Array.isArray(args) ? args : []++ return [text(command) ?? '', ...parts].join(' ').trim()+}++export function joinLocalServers({+ catalog,+ servers,+ status,+ toolCounts,+ usage+}: LocalJoinInput): LocalServerInput[] {+ return Object.entries(servers).map(([name, entry]) => {+ const bundled = catalog.find(candidate => candidate.name === name)+ const counts = toolCounts?.[name]+ const calls = usage?.[name]+ const raw = status[name] ?? 'unknown'++ return {+ canAuthenticate: canAuthenticate(entry, raw),+ connectorSlug: text(bundled?.connector_slug),+ description: text(bundled?.description),+ enabled: entry.enabled !== false,+ inCatalog: bundled !== undefined,+ name,+ status: raw,+ target: targetOf(entry),+ toolsOn: counts?.on,+ toolsTotal: counts?.total,+ unused: calls === undefined ? undefined : calls === 0+ }+ })+}++function authTypeOf(declared: string): ConnectorAuthType {+ if (declared === 'api_key') {+ return 'apiKey'+ }++ return declared === 'oauth' ? 'oauth' : 'none'+}++export function joinBundledEntries(catalog: readonly McpCatalogEntry[]): BundledEntryInput[] {+ return catalog.map(entry => ({+ authType: authTypeOf(entry.auth_type),+ connectorSlug: text(entry.connector_slug),+ description: text(entry.description),+ name: entry.name,+ needsEnv: entry.required_env.some(field => field.required)+ }))+}++const RUNTIME_STATUS = {+ configured: 'unknown',+ connected: 'ok',+ connecting: 'probing',+ disabled: 'off',+ failed: 'error',+ lazy: 'unknown'+} satisfies Record<McpRuntimeStatus, LocalServerStatus>++export interface PluginServerJoinInput {+ runtime: readonly McpServerRuntimeRow[]+ servers: readonly McpServerSummary[]+}++export function pluginServerRows({ runtime, servers }: PluginServerJoinInput): LocalServerInput[] {+ const live = new Map(runtime.map(row => [row.name, row]))++ return servers+ .filter(row => row.source === 'plugin')+ .map(row => {+ const state = live.get(row.name)+ const split = row.name.indexOf('__')++ return {+ enabled: row.enabled,+ name: row.name,+ plugin: row.plugin ?? '',+ status: state ? RUNTIME_STATUS[state.status] : 'unknown',+ target: text(row.url) ?? [row.command ?? '', ...row.args].join(' ').trim(),+ title: connectorTitle(split === -1 ? row.name : row.name.slice(split + 2)),+ toolsTotal: state?.tools+ }+ })+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/keys.ts b/apps/desktop/src/app/capabilities/connectors/data/keys.tsnew file mode 100644index 00000000000..6499a86245f--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/keys.ts@@ -0,0 +1,60 @@+import { type ProfileScope, profileScopeKey } from '@/hermes'+import { queryClient } from '@/lib/query-client'++export type ConnectorRead = 'accounts' | 'catalog' | 'list' | 'policy' | 'tools'++export const CONNECTORS_QUERY_ROOT = 'connectors'++const SECOND = 1000+const MINUTE = 60 * SECOND+const HOUR = 60 * MINUTE++interface ReadLifetime {+ focusRefetch: boolean+ persist: boolean+ staleTime: number+}++export const CONNECTOR_LIFETIMES = {+ accounts: { focusRefetch: true, persist: false, staleTime: 5 * MINUTE },+ catalog: { focusRefetch: false, persist: true, staleTime: 24 * HOUR },+ list: { focusRefetch: true, persist: true, staleTime: 5 * MINUTE },+ policy: { focusRefetch: false, persist: false, staleTime: 60 * SECOND },+ tools: { focusRefetch: false, persist: true, staleTime: 24 * HOUR }+} satisfies Record<ConnectorRead, ReadLifetime>++export const CONNECTOR_GC_TIME = Number.POSITIVE_INFINITY++const scoped = (scope: ProfileScope, ...rest: string[]) =>+ [CONNECTORS_QUERY_ROOT, profileScopeKey(scope), ...rest] as const++export const connectorsListQueryKey = (scope: ProfileScope) => scoped(scope, 'list')++export const connectorsCatalogQueryKey = (scope: ProfileScope) => scoped(scope, 'catalog')++export const connectorsAccountsQueryKey = (scope: ProfileScope) => scoped(scope, 'accounts')++export const connectorsPolicyQueryKey = (scope: ProfileScope) => scoped(scope, 'policy')++export const connectorToolsQueryKey = (scope: ProfileScope, slug: string) => scoped(scope, 'tools', slug)++export const pluginServersQueryKey = (scope: ProfileScope) => scoped(scope, 'plugin-servers')++export const PLUGIN_SERVERS_STALE_TIME = 5 * MINUTE++export const pluginProbeQueryKey = (scope: ProfileScope, name: string) => scoped(scope, 'plugin-probe', name)++export function invalidatePluginProbe(scope: ProfileScope, name: string): void {+ void queryClient.invalidateQueries({ queryKey: pluginProbeQueryKey(scope, name) })+}++export function invalidateConnectors(scope: ProfileScope, ...reads: [ConnectorRead, ...ConnectorRead[]]): void {+ for (const read of reads) {+ void queryClient.invalidateQueries({ queryKey: scoped(scope, read) })+ }+}++export function invalidateConnectorApp(scope: ProfileScope, slug: string): void {+ void queryClient.invalidateQueries({ queryKey: connectorToolsQueryKey(scope, slug) })+ void queryClient.invalidateQueries({ queryKey: connectorsListQueryKey(scope) })+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/mutations.ts b/apps/desktop/src/app/capabilities/connectors/data/mutations.tsnew file mode 100644index 00000000000..343fa6a744d--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/mutations.ts@@ -0,0 +1,243 @@+import type { ConnectionAnswer, ConnectorPolicyGetResult } from '@hermes/shared'+import { useCallback, useRef, useState } from 'react'++import type { ProfileScope } from '@/hermes'+import { translateNow } from '@/i18n'+import { queryClient } from '@/lib/query-client'+import { notifyError } from '@/store/notifications'++import type { SaveResult } from '../use-tools-editor'++import {+ $accountOperations,+ abandonConnect,+ type AccountOperation,+ clearAccountOperation,+ startAccountOperation+} from './account-operations'+import { memberDisabledTools, memberRevision, readPolicy } from './join'+import { connectorsPolicyQueryKey, invalidateConnectors } from './keys'+import {+ asConnectorError,+ connectAccountConnectors,+ connectorPolicy,+ type ConnectorRpcError,+ isConnectorReason,+ removeConnectorAccount,+ respondToAccountOperation,+ setConnectorPolicy+} from './rpc'++export type WriteOutcome = { error: ConnectorRpcError; ok: false } | { ok: true }++const failed = (error: ConnectorRpcError): WriteOutcome => ({ error, ok: false })++async function attempt<T>(run: () => Promise<T>): Promise<WriteOutcome> {+ try {+ await run()++ return { ok: true }+ } catch (error) {+ return failed(asConnectorError(error))+ }+}++interface WrittenRevision {+ after: string | undefined+ revision: string+}++const tokenFor = (written: null | WrittenRevision, seen: string | undefined): string | undefined =>+ written && written.after === seen ? written.revision : seen++const remember = (seen: string | undefined, revision: string | undefined): null | WrittenRevision =>+ revision === undefined ? null : { after: seen, revision }++function refusedSave(error: ConnectorRpcError): SaveResult {+ notifyError(error, translateNow('connectorsPage.tools.saveFailed'))++ return 'failed'+}++export interface ConnectorToolsSaver {+ onSave: (disabled: string[]) => Promise<SaveResult>+ reload: () => void+ theirs: string[] | null+}++export function useConnectorToolsSave(+ scope: ProfileScope,+ connector: string,+ seenRevision: string | undefined+): ConnectorToolsSaver {+ const [theirs, setTheirs] = useState<string[] | null>(null)+ const written = useRef<null | WrittenRevision>(null)++ const reload = useCallback(() => {+ setTheirs(null)+ invalidateConnectors(scope, 'policy')+ }, [scope])++ const onSave = useCallback(+ async (disabled: string[]): Promise<SaveResult> => {+ const expected = tokenFor(written.current, seenRevision)++ if (expected === undefined) {+ return refusedSave(asConnectorError(new Error(translateNow('connectorsPage.dialog.rulesReadOnly'))))+ }++ try {+ const result = await setConnectorPolicy(scope, { connector, disabled_tools: disabled, type: 'tools' }, expected)++ written.current = remember(seenRevision, result.revision)+ } catch (error) {+ if (!isConnectorReason(error, 'POLICY_CONFLICT')) {+ return refusedSave(asConnectorError(error))+ }++ try {+ const policy = readPolicy(await connectorPolicy(scope))++ written.current = remember(seenRevision, memberRevision(policy))+ setTheirs([...memberDisabledTools(policy, connector)])++ return 'conflict'+ } catch (reread) {+ return refusedSave(asConnectorError(reread))+ }+ }++ setTheirs(null)+ invalidateConnectors(scope, 'policy', 'list')++ return 'saved'+ },+ [connector, scope, seenRevision]+ )++ return { onSave, reload, theirs }+}++export interface ConnectorSwitch {+ pending: null | string+ setEnabled: (connector: string, enabled: boolean) => Promise<WriteOutcome>+}++export function useConnectorSwitch(scope: ProfileScope): ConnectorSwitch {+ const [pending, setPending] = useState<null | string>(null)+ const written = useRef<null | WrittenRevision>(null)++ const setEnabled = useCallback(+ async (connector: string, enabled: boolean): Promise<WriteOutcome> => {+ setPending(connector)++ try {+ return await attempt(async () => {+ const cached = queryClient.getQueryData<ConnectorPolicyGetResult>(connectorsPolicyQueryKey(scope))+ const seen = memberRevision(readPolicy(cached ?? (await connectorPolicy(scope))))+ const expected = tokenFor(written.current, seen)++ if (expected === undefined) {+ throw new Error(translateNow('connectorsPage.dialog.rulesReadOnly'))+ }++ const result = await setConnectorPolicy(scope, { connector, enabled, type: 'connector' }, expected)++ written.current = remember(seen, result.revision)+ invalidateConnectors(scope, 'policy', 'list')+ })+ } finally {+ setPending(null)+ }+ },+ [scope]+ )++ return { pending, setEnabled }+}++export interface AccountDisconnect {+ disconnect: (connectionId: string) => Promise<WriteOutcome>+ pending: boolean+}++export function useDisconnectAccount(scope: ProfileScope): AccountDisconnect {+ const [pending, setPending] = useState(false)++ const disconnect = useCallback(+ async (connectionId: string): Promise<WriteOutcome> => {+ setPending(true)++ try {+ return await attempt(async () => {+ await removeConnectorAccount(scope, connectionId)+ invalidateConnectors(scope, 'list', 'accounts')+ })+ } finally {+ setPending(false)+ }+ },+ [scope]+ )++ return { disconnect, pending }+}++export type ConnectOutcome = { error: ConnectorRpcError; ok: false } | { ok: true; operation: AccountOperation }++export interface ConnectorConnect {+ connect: (slug: string, options?: { reconnect?: boolean }) => Promise<ConnectOutcome>+ giveUp: (opId: string) => Promise<WriteOutcome>+ pending: null | string+}++export function useConnectConnector(scope: ProfileScope): ConnectorConnect {+ const [pending, setPending] = useState<null | string>(null)++ const connect = useCallback(+ async (slug: string, options?: { reconnect?: boolean }): Promise<ConnectOutcome> => {+ setPending(slug)++ try {+ const snapshot = await connectAccountConnectors(scope, [slug], options?.reconnect ?? false)++ return { ok: true, operation: startAccountOperation(scope, [slug], snapshot) }+ } catch (error) {+ return { error: asConnectorError(error), ok: false }+ } finally {+ setPending(null)+ }+ },+ [scope]+ )++ const respond = useCallback(+ (opId: string, answer: ConnectionAnswer): Promise<WriteOutcome> =>+ attempt(() => respondToAccountOperation(scope, opId, answer)),+ [scope]+ )++ const giveUp = useCallback(+ async (opId: string): Promise<WriteOutcome> => {+ const operation = $accountOperations.get()[opId]++ abandonConnect(operation?.connectors ?? [])+ clearAccountOperation(opId)++ const outcome = await respond(opId, { settled_by: 'continue' })++ for (const target of operation?.targets ?? []) {+ if (target.state !== 'connected' && target.connectionId) {+ await attempt(() => removeConnectorAccount(scope, target.connectionId))+ }+ }++ invalidateConnectors(scope, 'list', 'accounts')++ return outcome+ },+ [respond, scope]+ )++ return { connect, giveUp, pending }+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/persist.ts b/apps/desktop/src/app/capabilities/connectors/data/persist.tsnew file mode 100644index 00000000000..008b6b20486--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/persist.ts@@ -0,0 +1,283 @@+import { type ProfileScope, profileScopeKey } from '@/hermes'+import { queryClient } from '@/lib/query-client'+import { readJson, writeJson } from '@/lib/storage'+import { $freeTierStatus } from '@/store/free-tier'++import { MCP_CATALOG_KEY } from '../../mcp/mcp-status'+import type { LocalServerInput } from '../types'++import { CONNECTOR_LIFETIMES, type ConnectorRead, CONNECTORS_QUERY_ROOT } from './keys'++export type PersistedRead = 'bundled' | 'servers' | ConnectorRead++const persists = (read: PersistedRead): boolean =>+ read === 'bundled' || read === 'servers' || CONNECTOR_LIFETIMES[read].persist++const STORAGE_PREFIX = 'hermes.connectors.v4.'++const IDENTITY_KEY = 'hermes.connectors.identity.v4'++const PERSIST_MAX_BYTES = 256 * 1024++type PersistedIdentity = 'guest' | 'signed-in'++interface PersistedEntry {+ at: number+ data: unknown+}++type PersistedValue = PersistedEntry['data']++interface PersistedBlob {+ bundled?: PersistedEntry+ catalog?: PersistedEntry+ identity: PersistedIdentity+ list?: PersistedEntry+ servers?: PersistedEntry+ tools?: Record<string, PersistedEntry>+}++const keyFor = (scopeKey: string) => `${STORAGE_PREFIX}${scopeKey}`++const identityOf = (hasGuest: boolean): PersistedIdentity => (hasGuest ? 'guest' : 'signed-in')++function currentIdentity(): PersistedIdentity | null {+ const status = $freeTierStatus.get()++ return status ? identityOf(status.has_guest) : readJson<PersistedIdentity>(IDENTITY_KEY)+}++const READS: ReadonlySet<PersistedValue> = new Set(Object.keys(CONNECTOR_LIFETIMES))++function size(value: PersistedBlob | PersistedEntry): number {+ try {+ return JSON.stringify(value)?.length ?? 0+ } catch {+ return Number.POSITIVE_INFINITY+ }+}++function readBlob(scopeKey: string): PersistedBlob | null {+ const blob = readJson<PersistedBlob>(keyFor(scopeKey))++ if (!(blob instanceof Object) || Array.isArray(blob)) {+ return null+ }++ return blob.identity === currentIdentity() ? blob : null+}++const SLOTS = {+ bundled: 'bundled',+ catalog: 'catalog',+ list: 'list',+ servers: 'servers'+} satisfies Partial<Record<PersistedRead, keyof PersistedBlob>>++type SlotRead = keyof typeof SLOTS++function entryOf(blob: PersistedBlob, read: PersistedRead, slug: string | undefined): PersistedEntry | undefined {+ if (!persists(read)) {+ return undefined+ }++ if (read === 'tools') {+ return slug ? blob.tools?.[slug] : undefined+ }++ if (!(read in SLOTS)) {+ return undefined+ }++ // SAFETY: guarded by `read in SLOTS` on the line above, and every slot holds a PersistedEntry.+ return blob[SLOTS[read as SlotRead]] as PersistedEntry | undefined+}++export interface QuerySeed<T> {+ initialData?: T+ initialDataUpdatedAt?: number+}++export function seedOptions<T>(scopeKey: ProfileScope, read: PersistedRead, slug?: string): QuerySeed<T> {+ if (currentIdentity() === null) {+ return {}+ }++ const blob = readBlob(profileScopeKey(scopeKey))+ const entry = blob ? entryOf(blob, read, slug) : undefined++ if (!entry || !Number.isFinite(entry.at) || entry.data === undefined || entry.data === null) {+ return {}+ }++ // SAFETY: the caller names the read whose answer it stored, so the entry holds that read's own result.+ return { initialData: entry.data as T, initialDataUpdatedAt: entry.at }+}++function trimmed(blob: PersistedBlob): PersistedBlob {+ let tools = blob.tools++ while (tools !== undefined && size({ ...blob, tools }) > PERSIST_MAX_BYTES) {+ const oldest = Object.entries(tools).sort((a, b) => a[1].at - b[1].at)[0]++ if (!oldest) {+ break+ }++ const rest = { ...tools }+ delete rest[oldest[0]]+ tools = rest+ }++ return { ...blob, tools }+}++function store(scopeKey: string, read: PersistedRead, slug: string | undefined, entry: PersistedEntry): void {+ const identity = currentIdentity()++ if (identity === null || !persists(read) || size(entry) > PERSIST_MAX_BYTES) {+ return+ }++ const blob = readBlob(scopeKey) ?? { identity }++ if (read === 'tools') {+ if (!slug) {+ return+ }++ blob.tools = { ...blob.tools, [slug]: entry }+ } else {+ // SAFETY: `read` is not 'tools' here, and every other PersistedRead has a slot.+ blob[SLOTS[read as SlotRead]] = entry+ }++ writeJson(keyFor(scopeKey), trimmed({ ...blob, identity }))+}++interface ReadTarget {+ read: PersistedRead+ scopeKey: string+ slug: string | undefined+}++/* oxlint-disable anti-slop/no-runtime-typeof -- SAFETY: a react-query key is typed `readonly unknown[]`; this function is the one boundary that parses one into a ReadTarget. */+function targetOf(queryKey: readonly unknown[]): null | ReadTarget {+ const [root, scopeKey, read, slug] = queryKey++ if (typeof scopeKey !== 'string') {+ return null+ }++ if (root === MCP_CATALOG_KEY[0]) {+ return { read: 'bundled', scopeKey, slug: undefined }+ }++ if (root !== CONNECTORS_QUERY_ROOT || !READS.has(read)) {+ return null+ }++ // SAFETY: READS holds exactly the CONNECTOR_LIFETIMES keys, and `read` is one of them by the check above.+ return { read: read as ConnectorRead, scopeKey, slug: typeof slug === 'string' ? slug : undefined }+}+/* oxlint-enable anti-slop/no-runtime-typeof */++const WRITE_DELAY_MS = 500++interface PendingWrite extends ReadTarget {+ entry: PersistedEntry+}++export function startConnectorPersistence(): () => void {+ const pending = new Map<string, PendingWrite>()+ const written = new Map<string, number>()+ let timer: ReturnType<typeof setTimeout> | null = null++ const flush = () => {+ timer = null++ for (const [key, write] of pending) {+ store(write.scopeKey, write.read, write.slug, write.entry)+ written.set(key, write.entry.at)+ }++ pending.clear()+ }++ const stopCache = queryClient.getQueryCache().subscribe(event => {+ if (event.type !== 'updated' || event.action.type !== 'success') {+ return+ }++ const target = targetOf(event.query.queryKey)+ const { data, dataUpdatedAt } = event.query.state++ if (!target || data === undefined) {+ return+ }++ const key = `${target.scopeKey}\u0000${target.read}\u0000${target.slug ?? ''}`++ if (written.get(key) === dataUpdatedAt) {+ return+ }++ pending.set(key, { ...target, entry: { at: dataUpdatedAt, data } })+ timer ??= setTimeout(flush, WRITE_DELAY_MS)+ })++ const stopIdentity = $freeTierStatus.listen(status => {+ const identity = status ? identityOf(status.has_guest) : null++ if (identity !== null && identity !== readJson<PersistedIdentity>(IDENTITY_KEY)) {+ writeJson(IDENTITY_KEY, identity)+ }+ })++ return () => {+ stopCache()+ stopIdentity()++ if (timer !== null) {+ clearTimeout(timer)+ flush()+ }+ }+}++interface ServerSeed {+ enabled: boolean+ name: string+}++function isSeed(value: PersistedValue): value is ServerSeed {+ if (value === null || !(value instanceof Object)) {+ return false+ }++ // SAFETY: an object here; the two field checks below are what make it a ServerSeed.+ const seed = value as Partial<ServerSeed>++ // oxlint-disable-next-line anti-slop/no-runtime-typeof -- SAFETY: `seed` is a value read back from localStorage; this line is where it becomes a ServerSeed.+ return typeof seed.name === 'string' && typeof seed.enabled === 'boolean'+}++export function storeLocalServers(scope: ProfileScope, servers: readonly LocalServerInput[]): void {+ const seeds: ServerSeed[] = servers.map(({ enabled, name }) => ({ enabled, name }))++ store(profileScopeKey(scope), 'servers', undefined, { at: Date.now(), data: seeds })+}++export function seedLocalServers(scope: ProfileScope): LocalServerInput[] {+ const { initialData } = seedOptions<unknown>(scope, 'servers')++ if (!Array.isArray(initialData)) {+ return []+ }++ return initialData.filter(isSeed).map(seed => ({ ...seed, status: 'unknown', target: '' }))+}++export function clearPersisted(scope: ProfileScope): void {+ writeJson(keyFor(profileScopeKey(scope)), null)+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/portal.ts b/apps/desktop/src/app/capabilities/connectors/data/portal.tsnew file mode 100644index 00000000000..fb11dfbab69--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/portal.ts@@ -0,0 +1,29 @@+import { openExternalLink } from '@/lib/external-link'++import { FALLBACK_PORTAL_URL } from '../../../settings/billing/use-billing-state'++const CONNECTORS_PATH = '/connectors'++const FALLBACK_CONNECTORS_ADMIN_URL = `${FALLBACK_PORTAL_URL}${CONNECTORS_PATH}`++const adminUrl = (base: string): string => {+ const origin = base.replace(/\/+$/, '')++ return origin ? `${origin}${CONNECTORS_PATH}` : FALLBACK_CONNECTORS_ADMIN_URL+}++export async function openConnectorsAdmin(): Promise<void> {+ let url = FALLBACK_CONNECTORS_ADMIN_URL++ try {+ const status = await window.hermesDesktop?.cloud?.status()++ if (status) {+ url = adminUrl(status.portalBaseUrl)+ }+ } catch {+ // The fallback still opens, and a portal link is not worth a notice.+ }++ openExternalLink(url)+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/prefetch.ts b/apps/desktop/src/app/capabilities/connectors/data/prefetch.tsnew file mode 100644index 00000000000..edb69ccdb84--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/prefetch.ts@@ -0,0 +1,44 @@+import { useEffect, useMemo } from 'react'++import type { ProfileScope } from '@/hermes'+import { queryClient } from '@/lib/query-client'++import type { ConnectorCardModel } from '../types'++import { connectorToolsQueryOptions } from './queries'++const PREFETCH_LIMIT = 3++export function prefetchConnectorTools(scope: ProfileScope, slug: string): void {+ void queryClient.prefetchQuery(connectorToolsQueryOptions(scope, slug))+}++export function usePrefetchConnectedTools(scope: ProfileScope, cards: readonly ConnectorCardModel[]): void {+ const slugs = useMemo(+ () => cards.filter(card => card.ways.hosted?.state === 'connected').map(card => card.slug),+ [cards]+ )++ useEffect(() => {+ let stopped = false+ const queue = [...slugs]++ const next = async (): Promise<void> => {+ const slug = queue.shift()++ if (slug === undefined || stopped) {+ return+ }++ await queryClient.prefetchQuery(connectorToolsQueryOptions(scope, slug))++ return next()+ }++ void Promise.all(Array.from({ length: Math.min(PREFETCH_LIMIT, queue.length) }, () => next()))++ return () => {+ stopped = true+ }+ }, [scope, slugs])+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/queries.ts b/apps/desktop/src/app/capabilities/connectors/data/queries.tsnew file mode 100644index 00000000000..196aac61bc3--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/queries.ts@@ -0,0 +1,227 @@+import type { ConnectorAccountRow, ConnectorToolsResult } from '@hermes/shared'+import { useMutation, useQuery } from '@tanstack/react-query'+import { useCallback, useEffect, useMemo } from 'react'++import type { ProfileScope } from '@/hermes'+import { translateNow } from '@/i18n'+import { isMissingRpcMethod, isOutOfSyncRpcParams } from '@/lib/gateway-rpc'+import { queryClient } from '@/lib/query-client'+import { notifyError } from '@/store/notifications'++import { hostedPhase } from '../derive'+import { toolReadStatus } from '../derive-tools'+import type { HostedConnectorInput, HostedPhase, LocalServerInput, ToolInput, ToolsEditorStatus } from '../types'++import {+ type ConnectorPolicyView,+ connectorTitles,+ EMPTY_POLICY,+ joinHostedConnectors,+ pluginServerRows,+ readPolicy+} from './join'+import {+ CONNECTOR_GC_TIME,+ CONNECTOR_LIFETIMES,+ connectorsAccountsQueryKey,+ connectorsCatalogQueryKey,+ connectorsListQueryKey,+ connectorsPolicyQueryKey,+ connectorToolsQueryKey,+ invalidateConnectorApp,+ invalidateConnectors,+ PLUGIN_SERVERS_STALE_TIME,+ pluginServersQueryKey+} from './keys'+import { clearPersisted, seedOptions } from './persist'+import {+ asConnectorError,+ connectorAccounts,+ connectorCatalog,+ connectorPolicy,+ connectorTools,+ listConnectors,+ listMcpServers,+ mcpServerStatus+} from './rpc'++const read = (of: keyof typeof CONNECTOR_LIFETIMES) => ({+ gcTime: CONNECTOR_GC_TIME,+ refetchOnWindowFocus: CONNECTOR_LIFETIMES[of].focusRefetch,+ retry: false,+ staleTime: CONNECTOR_LIFETIMES[of].staleTime+})++export interface HostedConnectorsView {+ accounts: readonly ConnectorAccountRow[]+ listSlugs: ReadonlySet<string>+ phase: HostedPhase+ policy: ConnectorPolicyView+ refetch: () => void+ retryRules: () => void+ rows: HostedConnectorInput[]+ rulesFailed: boolean+ rulesSignedOut: boolean+ titles: Record<string, string>+}++export function useHostedConnectors(scope: ProfileScope): HostedConnectorsView {+ const listSeed = useMemo(() => seedOptions<Awaited<ReturnType<typeof listConnectors>>>(scope, 'list'), [scope])++ const catalogSeed = useMemo(+ () => seedOptions<Awaited<ReturnType<typeof connectorCatalog>>>(scope, 'catalog'),+ [scope]+ )++ const list = useQuery({+ ...read('list'),+ ...listSeed,+ queryFn: () => listConnectors(scope).catch(reportVersionSkew),+ queryKey: connectorsListQueryKey(scope)+ })++ const catalog = useQuery({+ ...read('catalog'),+ ...catalogSeed,+ queryFn: () => connectorCatalog(scope),+ queryKey: connectorsCatalogQueryKey(scope)+ })++ const accounts = useQuery({+ ...read('accounts'),+ queryFn: () => connectorAccounts(scope),+ queryKey: connectorsAccountsQueryKey(scope)+ })++ const policy = useQuery({+ ...read('policy'),+ queryFn: () => connectorPolicy(scope),+ queryKey: connectorsPolicyQueryKey(scope)+ })++ const listError = list.error === null ? null : asConnectorError(list.error)+ const policyError = policy.error === null ? null : asConnectorError(policy.error)+ const rulesFailed = policyError !== null++ const policyView = useMemo(() => (policy.data ? readPolicy(policy.data) : EMPTY_POLICY), [policy.data])++ const joined = useMemo(() => {+ const input = {+ accounts: accounts.data?.accounts ?? [],+ catalog: catalog.data?.connectors ?? [],+ list: list.data?.connectors ?? [],+ policy: policyView,+ rulesReadable: !rulesFailed+ }++ return { rows: joinHostedConnectors(input), titles: connectorTitles(input) }+ }, [accounts.data, catalog.data, list.data, policyView, rulesFailed])++ const phase = hostedPhase({+ available: list.data?.available,+ errored: listError !== null,+ pending: list.isPending,+ reason: listError?.reason ?? null+ })++ const blanked = phase === 'signedOut' || phase === 'unavailable'++ useEffect(() => {+ if (phase === 'signedOut') {+ clearPersisted(scope)+ }+ }, [phase, scope])++ const listSlugs = useMemo(+ () =>+ new Set(blanked ? [] : (list.data?.connectors ?? []).flatMap(row => (row.connector ? [row.connector] : []))),+ [blanked, list.data]+ )++ const refetch = useCallback(() => invalidateConnectors(scope, 'accounts', 'catalog', 'list', 'policy'), [scope])++ const retryRules = useCallback(() => invalidateConnectors(scope, 'policy'), [scope])++ return {+ accounts: accounts.data?.accounts ?? [],+ listSlugs,+ phase,+ policy: policyView,+ refetch,+ retryRules,+ rows: blanked ? [] : joined.rows,+ rulesFailed,+ rulesSignedOut: policyError?.reason === 'NEEDS_NOUS_AUTH',+ titles: joined.titles+ }+}++const NO_PLUGIN_SERVERS: LocalServerInput[] = []++export function usePluginServers(scope: ProfileScope): LocalServerInput[] {+ const plugins = useQuery({+ gcTime: CONNECTOR_GC_TIME,+ queryFn: async () => {+ const [list, runtime] = await Promise.all([listMcpServers(scope), mcpServerStatus(scope)])++ return pluginServerRows({ runtime: runtime.servers, servers: list.servers })+ },+ queryKey: pluginServersQueryKey(scope),+ retry: false,+ staleTime: PLUGIN_SERVERS_STALE_TIME+ })++ return plugins.data ?? NO_PLUGIN_SERVERS+}++function reportVersionSkew(cause: unknown): never {+ if (isMissingRpcMethod(cause) || isOutOfSyncRpcParams(cause instanceof Error ? cause : String(cause))) {+ notifyError(cause, translateNow('connectorsPage.page.hostedFailedTitle'))+ }++ throw cause+}++export function connectorToolsQueryOptions(scope: ProfileScope, slug: string) {+ return {+ ...read('tools'),+ ...seedOptions<ConnectorToolsResult>(scope, 'tools', slug),+ queryFn: () => connectorTools(scope, slug),+ queryKey: connectorToolsQueryKey(scope, slug)+ }+}++export interface ConnectorToolsView {+ refresh: () => void+ retry: () => void+ signedOut: boolean+ status: ToolsEditorStatus | null+ tools: ToolInput[]+}++export function useConnectorTools(scope: ProfileScope, slug: null | string, listHasApp: boolean): ConnectorToolsView {+ const key = connectorToolsQueryKey(scope, slug ?? '')+ const options = useMemo(() => connectorToolsQueryOptions(scope, slug ?? ''), [scope, slug])++ const tools = useQuery({ ...options, enabled: slug !== null })++ const revalidate = useMutation({+ mutationFn: () => connectorTools(scope, slug ?? '', true),+ onError: error => notifyError(error, translateNow('connectorsPage.page.refreshFailed')),+ onSuccess: data => queryClient.setQueryData(key, data)+ })++ const error = tools.error === null ? null : asConnectorError(tools.error)+ const reason = error === null ? null : (error.reason ?? 'CONNECTOR_REQUEST_FAILED')++ return {+ refresh: () => revalidate.mutate(),+ retry: () => invalidateConnectorApp(scope, slug ?? ''),+ signedOut: reason === 'NEEDS_NOUS_AUTH',+ status:+ slug === null+ ? null+ : toolReadStatus({ hasData: tools.data !== undefined, listHasApp, pending: tools.isPending, reason }),+ tools: tools.data?.tools ?? []+ }+}diff --git a/apps/desktop/src/app/capabilities/connectors/data/rpc.ts b/apps/desktop/src/app/capabilities/connectors/data/rpc.tsnew file mode 100644index 00000000000..cf6bddcae6b--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/data/rpc.ts@@ -0,0 +1,152 @@+import type {+ AccountOwner,+ ConnectionAnswer,+ ConnectorChange,+ ConnectorErrorReason,+ RpcMethods,+ ToolsChange+} from '@hermes/shared'+import { JsonRpcGatewayError } from '@hermes/shared'++import type { ProfileScope } from '@/hermes'+import { requestGatewayForAgent } from '@/store/gateway'++export type { ConnectorErrorReason }++export class ConnectorRpcError extends Error {+ readonly code: number | undefined+ readonly reason: ConnectorErrorReason | undefined++ constructor(message: string, code?: number, reason?: ConnectorErrorReason) {+ super(message)+ this.name = 'ConnectorRpcError'+ this.code = code+ this.reason = reason+ }+}++interface ConnectorErrorData {+ reason?: ConnectorErrorReason+}++function reasonOf(error: Error): ConnectorErrorReason | undefined {+ if (!(error instanceof JsonRpcGatewayError)) {+ return undefined+ }++ // SAFETY: `error.data` is the gateway's own `error.data` object; an absent or malformed `reason` reads as undefined.+ const data = (error.data ?? {}) as ConnectorErrorData++ return data.reason ?? undefined+}++const asError = (cause: unknown): Error => (cause instanceof Error ? cause : new Error(String(cause)))++export function asConnectorError(cause: unknown): ConnectorRpcError {+ const error = asError(cause)++ if (error instanceof ConnectorRpcError) {+ return error+ }++ const code = error instanceof JsonRpcGatewayError ? error.code : undefined++ return new ConnectorRpcError(error.message, code, reasonOf(error))+}++export function isConnectorReason(cause: unknown, ...reasons: readonly ConnectorErrorReason[]): boolean {+ const error = asError(cause)+ const reason = error instanceof ConnectorRpcError ? error.reason : reasonOf(error)++ return reason !== undefined && reasons.includes(reason)+}++const ACCOUNT_OWNER: AccountOwner = { type: 'account' }++const CONNECTOR_TIMEOUT_MS = 45_000++interface GatewayRoute {+ connectionId: null | string+ profile: string+}++function routeOf(scope: ProfileScope): GatewayRoute {+ if (scope instanceof Object) {+ return {+ connectionId: (scope.connectionId ?? '').trim() || null,+ profile: (scope.profile ?? '').trim()+ }+ }++ return { connectionId: null, profile: (scope ?? '').trim() }+}++type Urgency = 'background' | 'foreground'++type GatewayParams = NonNullable<Parameters<typeof requestGatewayForAgent>[3]>++async function call<M extends keyof RpcMethods>(+ scope: ProfileScope,+ method: M,+ params: RpcMethods[M]['params'],+ urgency: Urgency = 'background'+): Promise<RpcMethods[M]['result']> {+ const { connectionId, profile } = routeOf(scope)++ try {+ // SAFETY: every `RpcMethods[M]['params']` is a generated object type, which is the record the router takes.+ const payload = params as RpcMethods[M]['params'] & GatewayParams++ return await requestGatewayForAgent<RpcMethods[M]['result']>(+ connectionId,+ profile,+ method,+ payload,+ CONNECTOR_TIMEOUT_MS,+ undefined,+ { spawnPriority: urgency }+ )+ } catch (error) {+ throw asConnectorError(error)+ }+}++export const listConnectors = (scope: ProfileScope) => call(scope, 'connectors.list', { owner: ACCOUNT_OWNER })++export const connectorCatalog = (scope: ProfileScope) => call(scope, 'connectors.catalog', {})++export const connectorAccounts = (scope: ProfileScope, connector?: string) =>+ call(scope, 'connectors.accounts', connector === undefined ? {} : { connector })++export const connectorPolicy = (scope: ProfileScope) => call(scope, 'connectors.policy.get', {})++export const connectorTools = (scope: ProfileScope, slug: string, refresh = false) =>+ call(scope, 'connectors.tools', { refresh, slug })++export const accountOperationStatus = (scope: ProfileScope, opId: string) =>+ call(scope, 'connectors.operation.status', { op_id: opId, owner: ACCOUNT_OWNER })++export const setConnectorPolicy = (+ scope: ProfileScope,+ change: ConnectorChange | ToolsChange,+ expectedRevision: string+) => call(scope, 'connectors.policy.set', { change, expected_revision: expectedRevision }, 'foreground')++export const removeConnectorAccount = (scope: ProfileScope, connectionId: string) =>+ call(scope, 'connectors.accounts.remove', { connection_id: connectionId }, 'foreground')++export const connectAccountConnectors = (scope: ProfileScope, connectors: readonly string[], reconnect = false) =>+ call(scope, 'connectors.connect', { connectors: [...connectors], owner: ACCOUNT_OWNER, reconnect }, 'foreground')++export const wakeAccountOperation = (scope: ProfileScope, opId: string) =>+ call(scope, 'connectors.operation.wake', { op_id: opId, owner: ACCOUNT_OWNER }, 'foreground')++export const respondToAccountOperation = (scope: ProfileScope, opId: string, result: ConnectionAnswer) =>+ call(scope, 'connection.respond', { op_id: opId, owner: ACCOUNT_OWNER, result }, 'foreground')++export const setMcpBearerToken = (scope: ProfileScope, name: string, value: string) =>+ call(scope, 'mcp.servers.set_api_key', { name, value }, 'foreground')++export const listMcpServers = (scope: ProfileScope) => call(scope, 'mcp.servers.list', {})++export const mcpServerStatus = (scope: ProfileScope) => call(scope, 'mcp.servers.status', {})diff --git a/apps/desktop/src/app/capabilities/connectors/derive-page.ts b/apps/desktop/src/app/capabilities/connectors/derive-page.tsnew file mode 100644index 00000000000..7127324435c--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/derive-page.ts@@ -0,0 +1,94 @@+import type {+ ConnectorCardModel,+ ConnectorGroupId,+ ConnectorGroupModel,+ ConnectorPageModel,+ ConnectorSegmentModel,+ ConnectorsFilter,+ ConnectorState+} from './types'++const STATE_RANK = {+ available: 5,+ broken: 0,+ connected: 4,+ connecting: 3,+ expired: 1,+ off: 6,+ unknown: 2+} satisfies Record<ConnectorState, number>++const GROUP_OF = {+ available: 'available',+ broken: 'connected',+ connected: 'connected',+ connecting: 'connected',+ expired: 'connected',+ off: 'off',+ unknown: 'connected'+} satisfies Record<ConnectorState, ConnectorGroupId>++const GROUP_ORDER: readonly ConnectorGroupId[] = ['connected', 'local', 'available', 'off']++export function groupIdOf(card: ConnectorCardModel): ConnectorGroupId {+ return card.residency === 'local' && card.state !== 'available' ? 'local' : GROUP_OF[card.state]+}++function byStateThenName(a: ConnectorCardModel, b: ConnectorCardModel): number {+ return STATE_RANK[a.state] - STATE_RANK[b.state] || a.name.localeCompare(b.name)+}++export function cardMatchesQuery(card: ConnectorCardModel, query: string): boolean {+ const needle = query.trim().toLowerCase()++ return needle.length === 0 || card.slug.toLowerCase().includes(needle) || card.name.toLowerCase().includes(needle)+}++function groupCards(cards: readonly ConnectorCardModel[]): ConnectorGroupModel[] {+ const buckets = new Map<ConnectorGroupId, ConnectorCardModel[]>()++ for (const card of cards) {+ const id = groupIdOf(card)+ const bucket = buckets.get(id)++ if (bucket) {+ bucket.push(card)+ } else {+ buckets.set(id, [card])+ }+ }++ return GROUP_ORDER.filter(id => (buckets.get(id)?.length ?? 0) > 0).map(id => ({+ cards: [...buckets.get(id)!].sort(byStateThenName),+ id+ }))+}++export function showsAttentionFirst({ cards }: ConnectorGroupModel): boolean {+ return cards.length > 1 && cards.some(card => card.state === 'broken' || card.state === 'expired')+}++export function derivePage(+ cards: readonly ConnectorCardModel[],+ { query, segment }: ConnectorsFilter+): ConnectorPageModel {+ const matches = cards.filter(card => cardMatchesQuery(card, query))+ const groups = groupCards(matches)++ const segments: ConnectorSegmentModel[] = matches.length === 0 ? [] : [{ count: matches.length, id: 'all' }]++ for (const group of groups) {+ segments.push({ count: group.cards.length, id: group.id })+ }++ const shownSegment = segments.some(candidate => candidate.id === segment) ? segment : 'all'+ const chosen = shownSegment === 'all' ? groups : groups.filter(group => group.id === shownSegment)+ const shown = chosen.reduce((total, group) => total + group.cards.length, 0)++ return {+ groups: chosen,+ hiddenMatches: shownSegment === 'all' || query.trim() === '' ? 0 : matches.length - shown,+ segment: shownSegment,+ segments+ }+}diff --git a/apps/desktop/src/app/capabilities/connectors/derive-tools.ts b/apps/desktop/src/app/capabilities/connectors/derive-tools.tsnew file mode 100644index 00000000000..9572c0ef9cd--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/derive-tools.ts@@ -0,0 +1,312 @@+import { FACET_ORDER, HINT_ORDER } from './hint-vocabulary'+import type {+ ConflictDifference,+ FacetSummaryRow,+ QuickAction,+ QuickActionId,+ ToolInput,+ ToolRowModel,+ ToolsEditorCounts,+ ToolsEditorStatus,+ ToolsFilter+} from './types'++export const UNCATEGORISED = '__uncategorised__'++export const TINY_CONNECTOR_MAX = 8++export const EMPTY_TOOLS_FILTER: ToolsFilter = {+ category: null,+ facet: null,+ hint: null,+ query: '',+ showDeprecated: false+}++export function isTinyConnector(tools: readonly ToolRowModel[]): boolean {+ return tools.length <= TINY_CONNECTOR_MAX+}++export function toolDisplayName(slug: string): string {+ const words = slug+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')+ .replace(/[_.\-/]+/g, ' ')+ .trim()++ return words.charAt(0).toUpperCase() + words.slice(1)+}++export function categoryLabel(name: string): string {+ return name.replace(/_/g, ' ')+}++export function toolInCategory(tool: ToolRowModel, category: string): boolean {+ return category === UNCATEGORISED ? tool.categories.length === 0 : tool.categories.includes(category)+}++export function toolMatchesQuery(tool: ToolRowModel, query: string): boolean {+ const needle = query.trim().toLowerCase()++ return needle.length === 0 || tool.slug.toLowerCase().includes(needle) || tool.name.toLowerCase().includes(needle)+}++export function filterTools(tools: readonly ToolRowModel[], filter: ToolsFilter): ToolRowModel[] {+ return tools.filter(+ tool =>+ (filter.showDeprecated || !tool.deprecated) &&+ toolMatchesQuery(tool, filter.query) &&+ (filter.facet === null || tool.facet === filter.facet) &&+ (filter.hint === null || tool.hints.includes(filter.hint)) &&+ (filter.category === null || toolInCategory(tool, filter.category))+ )+}++export interface CountedValue {+ count: number+ value: string+}++function countBy(tools: readonly ToolRowModel[], pick: (tool: ToolRowModel) => readonly string[]): Map<string, number> {+ const counts = new Map<string, number>()++ for (const tool of tools) {+ for (const value of pick(tool)) {+ counts.set(value, (counts.get(value) ?? 0) + 1)+ }+ }++ return counts+}++function ordered(counts: Map<string, number>, order: readonly string[]): CountedValue[] {+ const known = order.filter(value => counts.has(value)).map(value => ({ count: counts.get(value)!, value }))++ const rest = [...counts.keys()]+ .filter(value => !order.includes(value))+ .sort()+ .map(value => ({ count: counts.get(value)!, value }))++ return [...known, ...rest]+}++export function facetCounts(tools: readonly ToolRowModel[]): CountedValue[] {+ return ordered(+ countBy(tools, tool => [tool.facet]),+ FACET_ORDER+ )+}++export function facetChips(tools: readonly ToolRowModel[]): CountedValue[] {+ const counts = facetCounts(tools)++ return counts.length >= 2 ? counts : []+}++const FACET_ECHO_HINTS: readonly string[] = ['destructiveHint', 'readOnlyHint']++export function hintChips(tools: readonly ToolRowModel[]): CountedValue[] {+ const counts = ordered(+ countBy(tools, tool => tool.hints.filter(hint => !FACET_ECHO_HINTS.includes(hint))),+ HINT_ORDER+ )++ return counts.length >= 2 ? counts : []+}++export function categoryCounts(tools: readonly ToolRowModel[]): CountedValue[] {+ const counts = countBy(tools, tool => tool.categories)++ if (counts.size === 0) {+ return []+ }++ const none = tools.filter(tool => tool.categories.length === 0).length++ const named = [...counts.entries()]+ .map(([value, count]) => ({ count, value }))+ .sort((a, b) => b.count - a.count || a.value.localeCompare(b.value))++ return none > 0 ? [...named, { count: none, value: UNCATEGORISED }] : named+}++export function deprecatedCount(tools: readonly ToolRowModel[]): number {+ return tools.filter(tool => tool.deprecated).length+}++export interface ToolReadInput {+ hasData: boolean+ listHasApp: boolean+ pending: boolean+ reason: null | string+}++export function toolReadStatus({ hasData, listHasApp, pending, reason }: ToolReadInput): ToolsEditorStatus | null {+ if (reason === 'CONNECTOR_NOT_FOUND') {+ return listHasApp ? 'unavailable' : 'gone'+ }++ if (hasData) {+ return null+ }++ if (reason !== null) {+ return reason === 'NEEDS_NOUS_AUTH' ? 'signedOut' : 'unavailable'+ }++ return pending ? 'loading' : null+}++export function facetTools(tools: readonly ToolRowModel[], facet: string): string[] {+ return tools.filter(tool => tool.facet === facet && !tool.deprecated && tool.lockedBy === null).map(tool => tool.slug)+}++export function facetSummary(tools: readonly ToolRowModel[], isOn: (slug: string) => boolean): FacetSummaryRow[] {+ const live = tools.filter(tool => !tool.deprecated)++ return facetCounts(live).map(({ count, value }) => {+ const on = live.filter(tool => tool.facet === value && isOn(tool.slug)).length+ const switchable = facetTools(live, value).length++ return {+ facet: value,+ locked: switchable === 0,+ on,+ switchState: on === 0 ? 'off' : on === switchable ? 'on' : 'mixed',+ total: count+ }+ })+}++const plainWords = (value: string) =>+ value+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, ' ')+ .trim()++export function describesNothingNew(tool: ToolRowModel): boolean {+ const description = plainWords(tool.description)++ return description === '' || description === plainWords(tool.name)+}++export const QUICK_ACTIONS = [+ { facets: ['destructive'], id: 'no-destructive' },+ { facets: ['destructive', 'write'], id: 'read-only' },+ { facets: [], id: 'everything-on' }+] as const satisfies readonly QuickAction[]++const QUICK_ACTION_DISPLAY: readonly QuickActionId[] = ['read-only', 'no-destructive', 'everything-on']++export function quickActionById(id: QuickActionId): QuickAction {+ return QUICK_ACTIONS.find(action => action.id === id)!+}++export function isUntouchedByQuickActions(tool: ToolRowModel): boolean {+ return tool.deprecated || tool.facet === 'unclassified'+}++export function expandQuickAction(action: QuickAction, tools: readonly ToolRowModel[]): string[] {+ return tools+ .filter(tool => !isUntouchedByQuickActions(tool) && action.facets.includes(tool.facet) && tool.lockedBy === null)+ .map(tool => tool.slug)+}++export function sameSet(a: readonly string[], b: readonly string[]): boolean {+ if (a.length !== b.length) {+ return false+ }++ const seen = new Set(a)++ return b.every(value => seen.has(value))+}++export function availableQuickActions(tools: readonly ToolRowModel[]): QuickAction[] {+ const taken: string[][] = []+ const out: QuickAction[] = []++ for (const action of QUICK_ACTIONS) {+ if (action.id === 'everything-on') {+ out.push(action)++ continue+ }++ const expansion = expandQuickAction(action, tools)++ if (expansion.length === 0 || taken.some(previous => sameSet(previous, expansion))) {+ continue+ }++ taken.push(expansion)+ out.push(action)+ }++ return out.sort((a, b) => QUICK_ACTION_DISPLAY.indexOf(a.id) - QUICK_ACTION_DISPLAY.indexOf(b.id))+}++export function matchingQuickAction(+ disabled: readonly string[],+ tools: readonly ToolRowModel[],+ prefer: QuickActionId | null = null+): QuickAction | null {+ const bySlug = new Map(tools.map(tool => [tool.slug, tool]))++ const comparable = disabled.filter(slug => {+ const tool = bySlug.get(slug)++ return tool !== undefined && !isUntouchedByQuickActions(tool)+ })++ const matches = QUICK_ACTIONS.filter(action => {+ const expansion = expandQuickAction(action, tools)++ return action.id === 'everything-on'+ ? comparable.length === 0+ : expansion.length > 0 && sameSet(comparable, expansion)+ })++ if (matches.length === 0) {+ return null+ }++ return matches.find(action => action.id === prefer) ?? matches[0]+}++export function editorCounts(local: readonly string[], baseline: readonly string[]): ToolsEditorCounts {+ const before = new Set(baseline)+ const after = new Set(local)++ return {+ backOn: baseline.filter(slug => !after.has(slug)).length,+ off: local.filter(slug => !before.has(slug)).length+ }+}++export function conflictDifference(theirs: readonly string[], mine: readonly string[]): ConflictDifference {+ const mineSet = new Set(mine)+ const theirSet = new Set(theirs)++ return {+ theyOff: theirs.filter(slug => !mineSet.has(slug)).length,+ theyOn: mine.filter(slug => !theirSet.has(slug)).length+ }+}++export function toolRows(+ tools: readonly ToolInput[],+ disabled: ReadonlySet<string>,+ orgDisabled: ReadonlySet<string> = new Set()+): ToolRowModel[] {+ return tools.map(tool => ({+ categories: tool.categories,+ deprecated: tool.deprecated,+ description: tool.description,+ facet: tool.facet,+ hints: tool.hints,+ lockedBy: orgDisabled.has(tool.slug) ? 'org' : null,+ name: tool.name,+ on: !orgDisabled.has(tool.slug) && !disabled.has(tool.slug),+ slug: tool.slug+ }))+}diff --git a/apps/desktop/src/app/capabilities/connectors/derive.ts b/apps/desktop/src/app/capabilities/connectors/derive.tsnew file mode 100644index 00000000000..63f5d34b4d7--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/derive.ts@@ -0,0 +1,415 @@+import { connectorTitle } from '@/lib/connector-tools'++import type {+ BundledEntryInput,+ ConnectorCardModel,+ ConnectorFact,+ ConnectorReason,+ ConnectorsFilter,+ ConnectorState,+ ConnectorStateWord,+ ConnectorVerb,+ ConnectorWayHosted,+ ConnectorWayLocal,+ ConnectorWays,+ HostedConnectorInput,+ HostedPhase,+ LocalServerInput,+ LocalServerStatus+} from './types'++export const EMPTY_CONNECTORS_FILTER: ConnectorsFilter = { query: '', segment: 'all' }++interface Phase {+ reason: ConnectorReason['key'] | undefined+ state: ConnectorState+ verb: ConnectorVerb | undefined+}++const HOSTED_PHASES = {+ active: { reason: undefined, state: 'connected', verb: undefined },+ expired: { reason: 'reconnect', state: 'expired', verb: 'reconnect' },+ failed: { reason: 'reconnect', state: 'broken', verb: 'tryAgain' },+ inactive: { reason: 'reconnect', state: 'expired', verb: 'reconnect' },+ pending: { reason: 'finishSignIn', state: 'connecting', verb: 'stopWaiting' },+ revoked: { reason: 'reconnect', state: 'expired', verb: 'reconnect' }+} satisfies Record<string, Phase>++const UNKNOWN_HOSTED_PHASE: Phase = { reason: undefined, state: 'unknown', verb: undefined }++function hostedPhaseFor(status: string): Phase {+ if (!Object.hasOwn(HOSTED_PHASES, status)) {+ return UNKNOWN_HOSTED_PHASE+ }++ // SAFETY: guarded by `Object.hasOwn` on the line above.+ return HOSTED_PHASES[status as keyof typeof HOSTED_PHASES]+}++const LOCAL_PHASES = {+ error: { reason: 'serverError', state: 'broken', verb: 'openLogs' },+ 'needs-auth': { reason: 'serverNeedsAuth', state: 'broken', verb: 'authenticate' },+ off: { reason: undefined, state: 'off', verb: undefined },+ ok: { reason: undefined, state: 'connected', verb: undefined },+ probing: { reason: undefined, state: 'connecting', verb: undefined },+ unknown: { reason: undefined, state: 'connecting', verb: undefined }+} satisfies Record<LocalServerStatus, Phase>++const HOSTED_WORDS = {+ available: 'available',+ broken: 'couldNotConnect',+ connected: 'connected',+ connecting: 'connecting',+ expired: 'accessExpired',+ off: 'offForYou',+ unknown: 'connectionUnknown'+} satisfies Record<ConnectorState, ConnectorStateWord>++const LOCAL_WORDS = {+ available: 'available',+ broken: 'serverError',+ connected: 'serverOn',+ connecting: 'serverConnecting',+ expired: 'serverError',+ off: 'serverOff',+ unknown: 'serverConnecting'+} satisfies Record<ConnectorState, ConnectorStateWord>++export function hostedWay(row: HostedConnectorInput): ConnectorWayHosted {+ const base = {+ accountLabel: row.accountLabel,+ connected: row.connected,+ connectedAt: row.connectedAt,+ disabledTools: row.disabledTools+ }++ if (row.orgLocked) {+ return { ...base, offBy: 'org', state: 'off' }+ }++ if (!row.enabled) {+ return { ...base, offBy: 'me', state: 'off', verb: 'turnBackOn' }+ }++ const status = row.connectionStatus ?? 'active'+ const phase = row.connected ? hostedPhaseFor(status) : undefined++ if (!phase) {+ return { ...base, state: 'available', verb: 'connect' }+ }++ if (phase.state === 'connecting') {+ return {+ ...base,+ accountLabel: undefined,+ connectedAt: undefined,+ reason: { key: 'finishSignIn' },+ state: phase.state,+ verb: phase.verb+ }+ }++ return {+ ...base,+ fact:+ phase.state === 'connected' && row.toolsOff && row.toolsOff > 0+ ? { count: row.toolsOff, key: 'toolsOff' }+ : undefined,+ reason: phase.reason+ ? { key: phase.reason, text: phase.reason === 'reconnect' ? row.statusReason : undefined }+ : undefined,+ state: phase.state,+ verb: phase.verb+ }+}++function localFact(server: LocalServerInput, state: ConnectorState): ConnectorFact | undefined {+ if (state !== 'connected' || server.unused === true || server.toolsTotal === undefined) {+ return undefined+ }++ if (server.toolsOn === undefined) {+ return { count: server.toolsTotal, key: 'tools' }+ }++ return server.toolsOn < server.toolsTotal+ ? { count: server.toolsTotal, key: 'toolsSomeOn', on: server.toolsOn }+ : { count: server.toolsOn, key: 'toolsOn' }+}++export function localWay(server: LocalServerInput): ConnectorWayLocal {+ const status: LocalServerStatus = server.enabled ? server.status : 'off'+ const phase = LOCAL_PHASES[status]++ return {+ fact: localFact(server, phase.state),+ inCatalog: server.inCatalog,+ installed: true,+ plugin: server.plugin,+ reason: phase.reason ? { key: phase.reason } : undefined,+ serverEnabled: server.enabled,+ serverName: server.name,+ state: phase.state,+ target: server.target,+ unused: server.unused,+ verb: phase.verb === 'authenticate' && server.canAuthenticate === false ? 'openLogs' : phase.verb+ }+}++export function bundledWay(entry: BundledEntryInput): ConnectorWayLocal {+ return {+ authType: entry.authType,+ entryName: entry.name,+ inCatalog: true,+ installed: false,+ needsEnv: entry.needsEnv,+ state: 'available',+ verb: 'install'+ }+}++export function bothWaysOn({ hosted, local }: ConnectorWays): boolean {+ return (+ hosted?.state === 'connected' &&+ local?.installed === true &&+ local.serverEnabled === true &&+ local.state === 'connected'+ )+}++type Speaker = { kind: 'hosted'; way: ConnectorWayHosted } | { kind: 'local'; way: ConnectorWayLocal }++function speakerOf(ways: ConnectorWays): Speaker {+ if (ways.hosted && ways.hosted.state !== 'available') {+ return { kind: 'hosted', way: ways.hosted }+ }++ if (ways.local?.installed === true) {+ return { kind: 'local', way: ways.local }+ }++ return ways.hosted === null ? { kind: 'local', way: ways.local } : { kind: 'hosted', way: ways.hosted }+}++export function hostedStateWord(way: ConnectorWayHosted): ConnectorStateWord {+ return way.offBy === 'org' ? 'offByYourOrganisation' : HOSTED_WORDS[way.state]+}++function localWord(way: ConnectorWayLocal): ConnectorStateWord {+ if (way.reason?.key === 'serverNeedsAuth') {+ return 'serverNeedsAuth'+ }++ return way.state === 'connected' && way.unused === true ? 'serverOnUnused' : LOCAL_WORDS[way.state]+}++export interface MergeCardInput {+ description?: string+ inCatalog: boolean+ name: string+ slug: string+ ways: ConnectorWays+}++export function mergeCard({ description, inCatalog, name, slug, ways }: MergeCardInput): ConnectorCardModel {+ const speaker = speakerOf(ways)++ const base = {+ description,+ fact: speaker.way.fact,+ inCatalog: inCatalog || ways.local?.inCatalog === true,+ name,+ reason: speaker.way.reason,+ slug,+ ways+ }++ if (speaker.kind === 'hosted') {+ return {+ ...base,+ offBy: speaker.way.offBy,+ residency: 'hosted',+ state: speaker.way.state,+ stateWord: hostedStateWord(speaker.way),+ verb: speaker.way.verb+ }+ }++ return {+ ...base,+ offBy: speaker.way.state === 'off' ? 'me' : undefined,+ plugin: speaker.way.plugin,+ residency: 'local',+ state: speaker.way.state,+ stateWord: localWord(speaker.way),+ verb: speaker.way.verb+ }+}++export function forgetAbandoned(+ rows: readonly HostedConnectorInput[],+ abandoned: ReadonlySet<string>+): HostedConnectorInput[] {+ return rows.map(row =>+ abandoned.has(row.slug) && row.connectionStatus === 'pending'+ ? { ...row, accountLabel: undefined, connected: false, connectedAt: undefined, connectionStatus: undefined }+ : row+ )+}++export function localServerName(card: ConnectorCardModel): string {+ return card.ways.local?.serverName ?? card.slug+}++export type ConnectorTwinPill = 'alsoLocal' | 'hostedTwin' | null++export function twinPillOf({ residency, ways }: ConnectorCardModel): ConnectorTwinPill {+ if (residency === 'local') {+ return ways.hosted && ways.hosted.state !== 'off' ? 'hostedTwin' : null+ }++ return ways.local?.installed === true ? 'alsoLocal' : null+}++export interface DeriveCardsInput {+ bundled?: readonly BundledEntryInput[]+ hosted: readonly HostedConnectorInput[]+ local: readonly LocalServerInput[]+ titles?: Readonly<Record<string, string>>+}++interface CardParts {+ bundled?: BundledEntryInput+ hosted?: HostedConnectorInput+ local?: LocalServerInput+}++export const hostedCardKey = (slug: string) => `hosted:${slug}`++export const localCardKey = (name: string) => `local:${name}`++export const cardKey = (card: ConnectorCardModel): string =>+ card.ways.hosted === null ? localCardKey(card.slug) : hostedCardKey(card.slug)++const mergeKey = (connectorSlug: string | undefined, name: string) => connectorSlug ?? localCardKey(name)++function waysOf(parts: CardParts): ConnectorWays | null {+ const local = parts.local ? localWay(parts.local) : parts.bundled ? bundledWay(parts.bundled) : null++ if (parts.hosted) {+ return { hosted: hostedWay(parts.hosted), local }+ }++ return local ? { hosted: null, local } : null+}++function slotAt(parts: Map<string, CardParts>, key: string): CardParts {+ const found = parts.get(key)++ if (found) {+ return found+ }++ const fresh: CardParts = {}+ parts.set(key, fresh)++ return fresh+}++// The slug stays the hosted slug, or the server's config key, so a deep link can still address the card.+function slugOf({ bundled, hosted, local }: CardParts): string {+ return hosted?.slug ?? local?.name ?? bundled?.name ?? ''+}++function descriptionOf({ bundled, hosted, local }: CardParts): string | undefined {+ return hosted?.description ?? local?.description ?? bundled?.description+}++// An install must not rename the app: the bundled entry and the server it becomes read the same way.+function nameOf(+ { bundled, hosted, local }: CardParts,+ titles: Readonly<Record<string, string>>,+ slug: string+): string {+ const key = hosted?.slug ?? local?.connectorSlug ?? bundled?.connectorSlug ?? slug++ return titles[key] ?? local?.title ?? connectorTitle(local?.name ?? bundled?.name ?? slug)+}++function cardOf(slot: CardParts, titles: Readonly<Record<string, string>>): ConnectorCardModel | null {+ const ways = waysOf(slot)++ if (!ways) {+ return null+ }++ const slug = slugOf(slot)++ return mergeCard({+ description: descriptionOf(slot),+ inCatalog: slot.hosted?.inCatalog ?? false,+ name: nameOf(slot, titles, slug),+ slug,+ ways+ })+}++export function deriveCards({ bundled = [], hosted, local, titles = {} }: DeriveCardsInput): ConnectorCardModel[] {+ const parts = new Map<string, CardParts>()++ for (const row of hosted) {+ slotAt(parts, row.slug).hosted = row+ }++ for (const server of local) {+ slotAt(parts, mergeKey(server.connectorSlug, server.name)).local = server+ }++ for (const entry of bundled) {+ const slot = slotAt(parts, mergeKey(entry.connectorSlug, entry.name))++ // An installed server always beats the bundled entry of the same app.+ if (!slot.local) {+ slot.bundled = entry+ }+ }++ const cards: ConnectorCardModel[] = []++ for (const slot of parts.values()) {+ const card = cardOf(slot, titles)++ if (card) {+ cards.push(card)+ }+ }++ return cards+}++export interface HostedPhaseInput {+ available?: boolean+ errored: boolean+ pending: boolean+ reason: null | string+}++export function hostedPhase({ available, errored, pending, reason }: HostedPhaseInput): HostedPhase {+ if (reason === 'NEEDS_NOUS_AUTH') {+ return 'signedOut'+ }++ if (reason === 'CONNECTORS_UNAVAILABLE') {+ return 'unavailable'+ }++ if (errored) {+ return 'failed'+ }++ if (pending) {+ return 'loading'+ }++ return available === false ? 'unavailable' : 'ready'+}diff --git a/apps/desktop/src/app/capabilities/connectors/dialog-menu.tsx b/apps/desktop/src/app/capabilities/connectors/dialog-menu.tsxnew file mode 100644index 00000000000..95457447930--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/dialog-menu.tsx@@ -0,0 +1,60 @@+import { Button } from '@/components/ui/button'+import { Codicon } from '@/components/ui/codicon'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ dropdownMenuRow,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from '@/components/ui/dropdown-menu'+import { useI18n } from '@/i18n'+import { cn } from '@/lib/utils'++import { openConnectorsAdmin } from './data/portal'++export interface ConnectorDialogMenuProps {+ onDisconnect?: () => void+ onReconnect?: () => void+ onRefreshTools: () => void+}++export function ConnectorDialogMenu({ onDisconnect, onReconnect, onRefreshTools }: ConnectorDialogMenuProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button aria-label={copy.dialog.moreActions} size="icon-xs" variant="ghost">+ <Codicon name="ellipsis" size="0.8125rem" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {onReconnect ? (+ <DropdownMenuItem className={dropdownMenuRow} onSelect={onReconnect}>+ {copy.card.verb.reconnect}+ </DropdownMenuItem>+ ) : null}+ <DropdownMenuItem className={dropdownMenuRow} onSelect={onRefreshTools}>+ {copy.dialog.menuRefreshTools}+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem className={dropdownMenuRow} onSelect={() => void openConnectorsAdmin()}>+ {copy.dialog.orgLink}+ </DropdownMenuItem>+ {onDisconnect ? (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem+ className={cn(dropdownMenuRow, 'text-destructive focus:text-destructive')}+ onSelect={onDisconnect}+ >+ {copy.dialog.disconnect}+ </DropdownMenuItem>+ </>+ ) : null}+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/hint-vocabulary.ts b/apps/desktop/src/app/capabilities/connectors/hint-vocabulary.tsnew file mode 100644index 00000000000..0f73b4f669c--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/hint-vocabulary.ts@@ -0,0 +1,109 @@+export type VocabularyTone = 'danger' | 'neutral' | 'notice' | 'unknown'++export type VocabularyKey =+ | 'facetDestructive'+ | 'facetRead'+ | 'facetUnclassified'+ | 'facetWrite'+ | 'hintCreate'+ | 'hintDelete'+ | 'hintDestructive'+ | 'hintIdempotent'+ | 'hintOpenWorld'+ | 'hintReadOnly'+ | 'hintUpdate'++export interface VocabularyEntry {+ key: VocabularyKey+ tone: VocabularyTone+}++export interface VocabularyTag {+ key: VocabularyKey | null+ raw: string+ tone: VocabularyTone+}++export interface VocabularyCopy {+ label: string+ long: string+}++export type VocabularyStrings = Record<VocabularyKey, VocabularyCopy>++export const VOCABULARY = {+ createHint: { key: 'hintCreate', tone: 'notice' },+ deleteHint: { key: 'hintDelete', tone: 'danger' },+ destructive: { key: 'facetDestructive', tone: 'danger' },+ destructiveHint: { key: 'hintDestructive', tone: 'danger' },+ idempotentHint: { key: 'hintIdempotent', tone: 'neutral' },+ openWorldHint: { key: 'hintOpenWorld', tone: 'notice' },+ read: { key: 'facetRead', tone: 'neutral' },+ readOnlyHint: { key: 'hintReadOnly', tone: 'neutral' },+ unclassified: { key: 'facetUnclassified', tone: 'unknown' },+ updateHint: { key: 'hintUpdate', tone: 'neutral' },+ write: { key: 'facetWrite', tone: 'notice' }+} satisfies Record<string, VocabularyEntry>++function vocabularyEntry(raw: string): undefined | VocabularyEntry {+ if (!Object.hasOwn(VOCABULARY, raw)) {+ return undefined+ }++ // SAFETY: guarded by `Object.hasOwn` on the line above.+ return VOCABULARY[raw as keyof typeof VOCABULARY]+}++export const FACET_ORDER: readonly (keyof typeof VOCABULARY)[] = ['read', 'write', 'destructive', 'unclassified']++export const HINT_ORDER: readonly (keyof typeof VOCABULARY)[] = [+ 'readOnlyHint',+ 'createHint',+ 'updateHint',+ 'deleteHint',+ 'destructiveHint',+ 'idempotentHint',+ 'openWorldHint'+]++const MAX_LABEL = 8++export function shortenUnknown(raw: string): string {+ const stem = raw.trim().replace(/Hint$/, '')+ const word = stem.split(/[\s_\-.:/]+/).find(part => part.length > 0) ?? ''+ const head = /^[a-z]+|^[A-Z][a-z]*/.exec(word)?.[0] ?? ''++ if (head.length === 0) {+ return ''+ }++ return (head.charAt(0).toUpperCase() + head.slice(1)).slice(0, MAX_LABEL)+}++export function vocabularyTag(raw: string): VocabularyTag {+ const entry = vocabularyEntry(raw)++ if (entry) {+ return { key: entry.key, raw, tone: entry.tone }+ }++ return { key: shortenUnknown(raw).length === 0 ? 'facetUnclassified' : null, raw, tone: 'unknown' }+}++const FACET_SAYS = { destructive: 'destructiveHint' } satisfies Record<string, string>++const facetSays = (facet: string): string | undefined =>+ facet === 'destructive' ? FACET_SAYS.destructive : undefined++export function hintTags(hints: readonly string[], facet?: string): VocabularyTag[] {+ const said = facet === undefined ? undefined : facetSays(facet)+ const seen = new Set(hints.filter(hint => hint !== said))+ const known = HINT_ORDER.filter(hint => seen.has(hint))+ const rest = [...seen].filter(hint => !(hint in VOCABULARY))++ return [...known, ...rest].map(vocabularyTag)+}++export function tagCopy(tag: VocabularyTag, strings: VocabularyStrings): VocabularyCopy {+ return tag.key ? strings[tag.key] : { label: shortenUnknown(tag.raw), long: tag.raw }+}diff --git a/apps/desktop/src/app/capabilities/connectors/hosted-dialog.tsx b/apps/desktop/src/app/capabilities/connectors/hosted-dialog.tsxnew file mode 100644index 00000000000..921dfcbfe97--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/hosted-dialog.tsx@@ -0,0 +1,155 @@+import { useStore } from '@nanostores/react'+import { useState } from 'react'++import { SegmentedControl } from '@/components/ui/segmented-control'+import type { ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'+import { openFreeTierSignIn } from '@/store/free-tier-sign-in'++import type { McpServersController } from '../mcp/use-mcp-servers'++import { ConnectElement } from './connect-element'+import { ConnectorDialog } from './connector-dialog'+import {+ $accountOperations,+ type AccountOperation,+ accountOperationFor,+ clearAccountOperation+} from './data/account-operations'+import { openConnectorsAdmin } from './data/portal'+import { type HostedConnectorsView, useConnectorTools } from './data/queries'+import { bothWaysOn, localServerName } from './derive'+import { ConnectorDialogMenu } from './dialog-menu'+import type { InstallField } from './local-server-control'+import { HostedToolsPanel, LocalToolsPanel, orgDisabledCount } from './tools-panel'+import type { ConnectorCardModel } from './types'++export interface HostedConnectorDialogProps {+ card: ConnectorCardModel+ controller: McpServersController+ hosted: HostedConnectorsView+ installFields?: readonly InstallField[]+ installing?: boolean+ onClose: () => void+ onConnect: () => void+ onDisconnect: () => void+ onGiveUp: (opId: string) => void+ onInstall: (env: Record<string, string>) => void+ onReconnect: () => void+ onRemoveServer: () => void+ onToggleForMe: (next: boolean) => void+ onVerb: () => void+ profile: ProfileScope+ togglePending: boolean+}++export function HostedConnectorDialog({+ card,+ controller,+ hosted,+ installFields,+ installing,+ onClose,+ onConnect,+ onDisconnect,+ onGiveUp,+ onInstall,+ onReconnect,+ onRemoveServer,+ onToggleForMe,+ onVerb,+ profile,+ togglePending+}: HostedConnectorDialogProps) {+ const { t } = useI18n()+ const tools = useConnectorTools(profile, card.slug, hosted.listSlugs.has(card.slug))+ const operation = accountOperationFor(useStore($accountOperations), card.slug)+ const [form, setForm] = useState<'hosted' | 'local'>('hosted')++ const both = bothWaysOn(card.ways)++ const hostedPanel = (+ <HostedToolsPanel+ card={card}+ disabledTools={card.ways.hosted?.disabledTools}+ onDisconnect={onDisconnect}+ onRetryRules={hosted.retryRules}+ onSignIn={() => openFreeTierSignIn()}+ policy={hosted.policy}+ readOnly={hosted.rulesFailed}+ rulesSignedOut={hosted.rulesSignedOut}+ scope={profile}+ tools={tools}+ />+ )++ const element = stillOpen(operation) ? (+ <ConnectElement onStopWaiting={() => onGiveUp(operation.opId)} operation={operation} />+ ) : undefined++ return (+ <ConnectorDialog+ card={card}+ connectElement={element}+ installFields={installFields}+ installing={installing}+ menu={+ <ConnectorDialogMenu+ onDisconnect={card.ways.hosted?.connected === true ? onDisconnect : undefined}+ onReconnect={onReconnect}+ onRefreshTools={tools.refresh}+ />+ }+ onAuthenticate={() => void controller.authenticate(localServerName(card))}+ onConnect={onConnect}+ onDisconnect={onDisconnect}+ onInstall={onInstall}+ onOpenAdmin={() => void openConnectorsAdmin()}+ onOpenChange={next => {+ if (!next) {+ if (operation?.settled) {+ clearAccountOperation(operation.opId)+ }++ onClose()+ }+ }}+ onReconnect={onReconnect}+ onServerToggle={next => void controller.setServerEnabled(localServerName(card), next)}+ onToggleForMe={onToggleForMe}+ onVerb={onVerb}+ open+ orgDisabledCount={orgDisabledCount(hosted.policy, card.slug, tools.tools)}+ rulesReadOnly={hosted.rulesFailed}+ togglePending={togglePending}+ tools={+ both ? (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex shrink-0 items-center border-b border-(--ui-stroke-tertiary) px-3.5 py-1.5">+ <SegmentedControl+ onChange={setForm}+ options={[+ { id: 'hosted', label: t.connectorsPage.dialog.wayHosted },+ { id: 'local', label: t.connectorsPage.residencyLocal }+ ]}+ value={form}+ />+ </div>++ {form === 'hosted' ? (+ hostedPanel+ ) : (+ <LocalToolsPanel card={card} controller={controller} onRemove={onRemoveServer} />+ )}+ </div>+ ) : (+ hostedPanel+ )+ }+ />+ )+}++function stillOpen(operation: AccountOperation | null): operation is AccountOperation {+ return operation !== null && (!operation.settled || !operation.targets.every(target => target.state === 'connected'))+}diff --git a/apps/desktop/src/app/capabilities/connectors/local-dialog.tsx b/apps/desktop/src/app/capabilities/connectors/local-dialog.tsxnew file mode 100644index 00000000000..5599a1cdeb6--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/local-dialog.tsx@@ -0,0 +1,120 @@+import { compactNumber } from '@hermes/shared'+import { useLocation, useNavigate } from 'react-router'++import { PanelEmpty } from '@/app/overlays/panel'+import type { ProfileScope } from '@/hermes'+import { useI18n } from '@/i18n'++import type { McpServersController } from '../mcp/use-mcp-servers'++import { ConnectorDialog } from './connector-dialog'+import { invalidatePluginProbe } from './data/keys'+import { localServerName } from './derive'+import { ConnectorDialogMenu } from './dialog-menu'+import type { InstallField } from './local-server-control'+import { LocalAdvanced } from './local-slots'+import { PluginToolsPanel } from './plugin-tools-panel'+import { LocalToolsPanel } from './tools-panel'+import type { ConnectorCardModel } from './types'++export interface LocalConnectorDialogProps {+ card: ConnectorCardModel+ controller: McpServersController+ installFields?: readonly InstallField[]+ installing?: boolean+ onClose: () => void+ onConnect: () => void+ onInstall: (env: Record<string, string>) => void+ onReconnect: () => void+ onRemoveServer: () => void+ profile: ProfileScope+}++export function LocalConnectorDialog({+ card,+ controller,+ installFields,+ installing,+ onClose,+ onConnect,+ onInstall,+ onReconnect,+ onRemoveServer,+ profile+}: LocalConnectorDialogProps) {+ const { t } = useI18n()+ const name = localServerName(card)+ const openPlugins = useOpenPluginsTab()+ const plugin = card.plugin+ const installed = card.ways.local?.installed === true+ const owned = plugin === undefined && installed++ const refreshTools = () => {+ if (plugin === undefined) {+ void controller.runProbe(name)+ } else {+ invalidatePluginProbe(profile, name)+ }+ }++ return (+ <ConnectorDialog+ advanced={owned ? <LocalAdvanced controller={controller} name={name} onRemove={onRemoveServer} /> : undefined}+ card={card}+ cost={localCost(controller, name)}+ installFields={installFields}+ installing={installing}+ menu={<ConnectorDialogMenu onRefreshTools={refreshTools} />}+ onAuthenticate={() => void controller.authenticate(name)}+ onConnect={onConnect}+ onInstall={onInstall}+ onOpenChange={next => {+ if (!next) {+ onClose()+ }+ }}+ onReconnect={onReconnect}+ onServerToggle={next => void controller.setServerEnabled(name, next)}+ open+ tools={+ plugin !== undefined ? (+ <PluginToolsPanel card={card} onOpenPlugins={openPlugins} plugin={plugin} scope={profile} />+ ) : installed ? (+ <LocalToolsPanel card={card} controller={controller} onRemove={onRemoveServer} />+ ) : (+ <PanelEmpty+ description={t.connectorsPage.tools.notInstalledBody}+ icon="plug"+ title={t.connectorsPage.tools.title}+ />+ )+ }+ />+ )+}++function useOpenPluginsTab(): () => void {+ const navigate = useNavigate()+ const { hash, pathname, search } = useLocation()++ return () => {+ const params = new URLSearchParams(search)+ params.set('tab', 'plugins')+ navigate({ hash, pathname, search: `?${params.toString()}` })+ }+}++function localCost(controller: McpServersController, name: string) {+ const entry = controller.servers[name]++ if (!entry) {+ return undefined+ }++ const cost = controller.costFor(name, entry)++ return {+ tokensPerCall: cost.tokens === null ? undefined : compactNumber(cost.tokens),+ usesPerMonth: cost.uses === null ? undefined : compactNumber(cost.uses)+ }+}diff --git a/apps/desktop/src/app/capabilities/connectors/local-server-control.tsx b/apps/desktop/src/app/capabilities/connectors/local-server-control.tsxnew file mode 100644index 00000000000..4ee5fb5405b--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/local-server-control.tsx@@ -0,0 +1,98 @@+import { useState } from 'react'++import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Switch } from '@/components/ui/switch'+import type { McpCatalogEntry } from '@/hermes'+import { useI18n } from '@/i18n'++import type { ConnectorWayLocal } from './types'++export type InstallField = McpCatalogEntry['required_env'][number]++export function LocalServerControl({+ name,+ onAuthenticate,+ onServerToggle,+ way+}: {+ name: string+ onAuthenticate?: () => void+ onServerToggle?: (next: boolean) => void+ way: ConnectorWayLocal+}) {+ const { t } = useI18n()+ const copy = t.connectorsPage++ return (+ <div className="grid gap-2">+ <div className="flex items-center justify-between gap-2">+ <span className="min-w-0 flex-1 truncate text-[0.7rem] text-(--ui-text-tertiary)">+ {copy.card.state[way.serverEnabled === true ? 'serverOn' : 'serverOff']}+ </span>+ {onServerToggle ? (+ <Switch+ aria-label={way.serverEnabled === true ? copy.card.turnServerOff(name) : copy.card.turnServerOn(name)}+ checked={way.serverEnabled ?? false}+ onCheckedChange={onServerToggle}+ size="xs"+ />+ ) : null}+ </div>++ {way.verb === 'authenticate' && onAuthenticate ? (+ <Button className="justify-self-start" onClick={onAuthenticate} size="xs">+ {copy.card.verb.authenticate}+ </Button>+ ) : null}+ </div>+ )+}++export function LocalInstall({+ installFields = [],+ installing = false,+ onInstall+}: {+ installFields?: readonly InstallField[]+ installing?: boolean+ onInstall: (env: Record<string, string>) => void+}) {+ const { t } = useI18n()+ const [draft, setDraft] = useState<Record<string, string>>({})+ const missing = installFields.some(field => field.required === true && !(draft[field.name] ?? '').trim())++ return (+ <div className="grid justify-items-start gap-2">+ {installFields.length > 0 ? (+ <>+ <p className="text-[0.7rem] text-(--ui-text-tertiary)">{t.settings.mcp.catalogEnvRequired}</p>+ {installFields.map(field => (+ <label className="grid w-full gap-1" key={field.name}>+ <span className="text-[0.65rem] text-(--ui-text-secondary)">+ {field.prompt || field.name}+ {field.required ? ' *' : ''}+ </span>+ <Input+ className="h-7 text-xs"+ onChange={event => setDraft({ ...draft, [field.name]: event.currentTarget.value })}+ type="password"+ value={draft[field.name] ?? ''}+ />+ </label>+ ))}+ </>+ ) : null}++ <Button+ disabled={installing || missing}+ loading={installing}+ onClick={() => onInstall(draft)}+ size="xs"+ variant="outline"+ >+ {t.connectorsPage.card.verb.install}+ </Button>+ </div>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/local-slots.tsx b/apps/desktop/src/app/capabilities/connectors/local-slots.tsxnew file mode 100644index 00000000000..2b0c68bb791--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/local-slots.tsx@@ -0,0 +1,71 @@+import { Button } from '@/components/ui/button'+import { ConfirmDialog } from '@/components/ui/confirm-dialog'+import { useI18n } from '@/i18n'++import { McpJsonEditor, McpLogPane } from '../mcp/mcp-editor'+import type { McpServersController } from '../mcp/use-mcp-servers'++import { localServerName } from './derive'+import type { ConnectorCardModel } from './types'++export interface LocalAdvancedProps {+ controller: McpServersController+ name: string+ onRemove: () => void+}++export function LocalAdvanced({ controller, name, onRemove }: LocalAdvancedProps) {+ const { t } = useI18n()+ const m = t.settings.mcp++ return (+ <div className="grid min-h-0 gap-2">+ <div className="h-56 overflow-hidden rounded-md border border-(--ui-stroke-tertiary)">+ <McpJsonEditor controller={controller} highlightServer={name} />+ </div>++ <div className="h-40 overflow-hidden rounded-md border border-(--ui-stroke-tertiary)">+ <McpLogPane server={name} />+ </div>++ <Button className="justify-self-start text-destructive" onClick={onRemove} size="xs" variant="text">+ {m.remove}+ </Button>+ </div>+ )+}++export interface RemoveServerConfirmProps {+ card: ConnectorCardModel | null+ controller: McpServersController+ onClose: () => void+ onRemoved: () => void+}++export function RemoveServerConfirm({ card, controller, onClose, onRemoved }: RemoveServerConfirmProps) {+ const { t } = useI18n()+ const m = t.settings.mcp+ const name = card ? localServerName(card) : null++ return (+ <ConfirmDialog+ confirmLabel={m.remove}+ description={t.connectorsPage.dialog.removeServerBody}+ destructive+ onClose={onClose}+ onConfirm={async () => {+ if (!name) {+ return+ }++ if (!(await controller.removeServer(name))) {+ throw new Error(m.removeFailed)+ }++ onRemoved()+ }}+ open={card !== null}+ title={t.connectorsPage.dialog.removeServerTitle(card?.name ?? '')}+ />+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/plugin-tools-panel.tsx b/apps/desktop/src/app/capabilities/connectors/plugin-tools-panel.tsxnew file mode 100644index 00000000000..52382e23d85--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/plugin-tools-panel.tsx@@ -0,0 +1,108 @@+import { useQuery } from '@tanstack/react-query'+import { useMemo } from 'react'++import { PanelEmpty } from '@/app/overlays/panel'+import { Button } from '@/components/ui/button'+import { type ProfileScope, testMcpServer } from '@/hermes'+import { useI18n } from '@/i18n'+import { PROBE_TTL_MS } from '@/lib/mcp-probe-cache'++import { CONNECTOR_GC_TIME, pluginProbeQueryKey } from './data/keys'+import { localServerName } from './derive'+import { toolDisplayName, toolRows } from './derive-tools'+import { ToolsList } from './tools-list'+import type { ConnectorCardModel, ToolInput } from './types'+import { useToolsEditor } from './use-tools-editor'++const NOTHING_DISABLED: readonly string[] = []++export interface PluginToolsPanelProps {+ card: ConnectorCardModel+ onOpenPlugins: () => void+ plugin: string+ scope: ProfileScope+}++export function PluginToolsPanel({ card, onOpenPlugins, plugin, scope }: PluginToolsPanelProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage+ const name = localServerName(card)++ const probe = useQuery({+ gcTime: CONNECTOR_GC_TIME,+ queryFn: () => testMcpServer(name, scope),+ queryKey: pluginProbeQueryKey(scope, name),+ retry: false,+ staleTime: PROBE_TTL_MS+ })++ const inputs = useMemo<ToolInput[]>(+ () =>+ probe.data?.tools.map(tool => ({+ categories: [],+ deprecated: false,+ description: tool.description ?? '',+ facet: 'unclassified',+ hints: [],+ name: toolDisplayName(tool.name),+ slug: tool.name+ })) ?? [],+ [probe.data]+ )++ const rows = useMemo(() => toolRows(inputs, new Set()), [inputs])++ const editor = useToolsEditor({+ editorKey: name,+ onSave: async () => 'failed',+ savedDisabled: NOTHING_DISABLED,+ status: probe.isPending ? 'loading' : null,+ tools: rows+ })++ const failure = probe.error+ ? probe.error instanceof Error+ ? probe.error.message+ : String(probe.error)+ : probe.data && !probe.data.ok+ ? (probe.data.error ?? '')+ : null++ return (+ <div className="flex min-h-0 flex-1 flex-col">+ <div className="flex shrink-0 items-center gap-2 border-b border-(--ui-stroke-tertiary) px-3.5 py-1.5">+ <span className="min-w-0 flex-1 text-[0.7rem] text-(--ui-text-tertiary)">+ {copy.dialog.providedByPlugin(plugin)}+ </span>+ <Button onClick={onOpenPlugins} size="inline" variant="textStrong">+ {copy.dialog.openPlugins}+ </Button>+ </div>++ {failure === null ? (+ <ToolsList+ connectorName={card.name}+ editor={editor}+ listKey={name}+ onReload={() => void probe.refetch()}+ onRetry={() => void probe.refetch()}+ preview+ readOnly+ summaryTitle={card.state === 'connected' ? copy.tools.summaryTitle(card.name) : undefined}+ tools={rows}+ />+ ) : (+ <PanelEmpty+ action={+ <Button onClick={() => void probe.refetch()} size="inline" variant="textStrong">+ {copy.tools.retry}+ </Button>+ }+ description={failure}+ icon="warning"+ title={copy.tools.unavailableLine}+ />+ )}+ </div>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/tool-row.tsx b/apps/desktop/src/app/capabilities/connectors/tool-row.tsxnew file mode 100644index 00000000000..675a733114f--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/tool-row.tsx@@ -0,0 +1,146 @@+import type { ReactNode } from 'react'++import { DisclosureCaret } from '@/components/ui/disclosure-caret'+import { Switch } from '@/components/ui/switch'+import { Tip } from '@/components/ui/tooltip'+import { useI18n } from '@/i18n'+import { Lock } from '@/lib/icons'+import { cn } from '@/lib/utils'++import { describesNothingNew } from './derive-tools'+import { hintTags, tagCopy, vocabularyTag, type VocabularyTone } from './hint-vocabulary'+import type { ToolRowModel } from './types'++export const TOOL_ROW_HEIGHT = 30++const MAX_ROW_HINTS = 2++const TONE_CLASS = {+ danger: 'text-(--ui-red)',+ neutral: 'text-(--ui-text-secondary)',+ notice: 'text-(--ui-yellow)',+ unknown: 'text-(--ui-purple)'+} satisfies Record<VocabularyTone, string>++export interface ToolRowProps {+ expanded: boolean+ on: boolean+ onExpand: () => void+ onToggle: () => void+ preview?: boolean+ readOnly?: boolean+ tool: ToolRowModel+}++export function ToolRow({ expanded, on, onExpand, onToggle, preview = false, readOnly = false, tool }: ToolRowProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage.tools+ const locked = tool.lockedBy !== null+ const struck = locked || tool.deprecated+ const facet = vocabularyTag(tool.facet)+ const facetCopy = tagCopy(facet, t.connectorsPage.vocabulary)+ const hints = hintTags(tool.hints, tool.facet)+ const expandable = !describesNothingNew(tool)++ const line = (+ <>+ <span+ className={cn(+ 'min-w-0 truncate text-xs font-medium',+ struck ? 'text-(--ui-text-quaternary) line-through' : 'text-(--ui-text-primary)'+ )}+ >+ {tool.name}+ </span>++ <span className="flex shrink-0 items-center gap-1.5 text-[0.65rem] text-(--ui-text-quaternary)">+ {tool.facet === 'unclassified' ? null : (+ <Tip label={facetCopy.long}>+ <span className={cn('whitespace-nowrap', locked ? 'text-(--ui-text-quaternary)' : TONE_CLASS[facet.tone])}>+ {facetCopy.label}+ </span>+ </Tip>+ )}++ {locked ? (+ <span className="whitespace-nowrap">{copy.lockedHint}</span>+ ) : (+ <HintTags hints={hints.slice(0, MAX_ROW_HINTS)} more={Math.max(0, hints.length - MAX_ROW_HINTS)} />+ )}++ {expandable ? <DisclosureCaret className="text-(--ui-text-quaternary)" open={expanded} /> : null}+ </span>+ </>+ )++ return (+ <div+ className={cn('grid', locked && 'bg-muted/40', expanded && 'bg-(--ui-row-open-background)')}+ data-slot="tool-row"+ data-tool={tool.slug}+ >+ <div className="flex items-center gap-2.5 px-3.5" style={{ height: TOOL_ROW_HEIGHT }}>+ <span className="flex w-7 shrink-0 items-center">+ {preview ? null : locked ? (+ <Lock aria-hidden className="size-3 text-(--ui-text-quaternary)" />+ ) : (+ <Switch+ aria-label={on ? copy.turnToolOff(tool.name) : copy.turnToolOn(tool.name)}+ checked={on}+ disabled={readOnly}+ onCheckedChange={onToggle}+ size="xs"+ />+ )}+ </span>++ {expandable ? (+ <button+ aria-expanded={expanded}+ className="grid min-w-0 flex-1 grid-cols-[minmax(0,1fr)_auto] items-center gap-2.5 text-left outline-none focus-visible:ring-[0.1875rem] focus-visible:ring-ring/50"+ onClick={onExpand}+ type="button"+ >+ {line}+ <span className="sr-only">{expanded ? copy.hideDetails(tool.name) : copy.showDetails(tool.name)}</span>+ </button>+ ) : (+ <div className="grid min-w-0 flex-1 grid-cols-[minmax(0,1fr)_auto] items-center gap-2.5">{line}</div>+ )}+ </div>++ {expanded ? <ToolDetail hints={hints} tool={tool} /> : null}+ </div>+ )+}++function HintTags({ hints, more }: { hints: ReturnType<typeof hintTags>; more: number }) {+ const { t } = useI18n()+ const copy = t.connectorsPage++ return (+ <>+ {hints.map(hint => (+ <span className="whitespace-nowrap" key={hint.raw}>+ {tagCopy(hint, copy.vocabulary).label}+ </span>+ ))}+ {more > 0 ? <span className="whitespace-nowrap tabular-nums">{copy.tools.moreHints(more)}</span> : null}+ </>+ )+}++function ToolDetail({ hints, tool }: { hints: ReturnType<typeof hintTags>; tool: ToolRowModel }): ReactNode {+ const { t } = useI18n()++ return (+ <div className="grid gap-1 pb-2.5 pl-[3.625rem] pr-3.5">+ <p className="max-w-[60ch] text-[0.7rem] leading-relaxed text-(--ui-text-secondary)">{tool.description}</p>+ {hints.length > MAX_ROW_HINTS ? (+ <p className="text-[0.65rem] text-(--ui-text-quaternary)">+ {hints.map(hint => tagCopy(hint, t.connectorsPage.vocabulary).label).join(' · ')}+ </p>+ ) : null}+ </div>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/tools-filter-bar.tsx b/apps/desktop/src/app/capabilities/connectors/tools-filter-bar.tsxnew file mode 100644index 00000000000..f54ad356c38--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/tools-filter-bar.tsx@@ -0,0 +1,140 @@+import { Button } from '@/components/ui/button'+import { SearchField } from '@/components/ui/search-field'+import { Separator } from '@/components/ui/separator'+import { useI18n } from '@/i18n'+import type { Translations } from '@/i18n/types'+import { cn } from '@/lib/utils'++import { CategoryPicker } from './category-picker'+import type { CountedValue } from './derive-tools'+import { tagCopy, vocabularyTag } from './hint-vocabulary'+import type { QuickAction, QuickActionId, ToolsFilter } from './types'++function quickActionLabel(copy: Translations['connectorsPage']['tools'], id: QuickActionId): string {+ return {+ 'everything-on': copy.quickEverythingOn,+ 'no-destructive': copy.quickNoDestructive,+ 'read-only': copy.quickReadOnly+ }[id]+}++export interface ToolsFilterBarProps {+ categories: CountedValue[]+ currentAction: null | QuickAction+ facets: CountedValue[]+ filter: ToolsFilter+ hints: CountedValue[]+ onApplyQuickAction: (id: QuickActionId) => void+ onFilterChange: (next: ToolsFilter) => void+ onShowSummary: () => void+ quickActions: QuickAction[]+ tiny: boolean+ total: number+}++export function ToolsFilterBar({+ categories,+ currentAction,+ facets,+ filter,+ hints,+ onApplyQuickAction,+ onFilterChange,+ onShowSummary,+ quickActions,+ tiny,+ total+}: ToolsFilterBarProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage.tools+ const set = (patch: Partial<ToolsFilter>) => onFilterChange({ ...filter, ...patch })+ const chips = facets.length + hints.length + categories.length + quickActions.length++ return (+ <div className="grid shrink-0 gap-2 border-b border-(--ui-stroke-tertiary) bg-(--ui-bg-chrome) px-3.5 py-2">+ <div className="flex items-center gap-3">+ <span className="shrink-0 text-xs font-medium text-(--ui-text-primary)">{copy.title}</span>+ <span className="shrink-0 tabular-nums text-[0.7rem] text-(--ui-text-tertiary)">{total}</span>++ <Button className="shrink-0" onClick={onShowSummary} size="xs" variant="text">+ {copy.showSummary}+ </Button>++ {tiny ? null : (+ <SearchField+ containerClassName="min-w-0 flex-1"+ onChange={query => set({ query })}+ placeholder={copy.searchCountPlaceholder(total)}+ value={filter.query}+ />+ )}+ </div>++ {tiny || chips === 0 ? null : (+ <div className="flex flex-wrap items-center gap-1.5">+ {facets.map(entry => (+ <FilterChip+ count={entry.count}+ key={entry.value}+ label={tagCopy(vocabularyTag(entry.value), t.connectorsPage.vocabulary).label}+ onClick={() => set({ facet: filter.facet === entry.value ? null : entry.value })}+ selected={filter.facet === entry.value}+ />+ ))}++ {facets.length > 0 && hints.length > 0 ? <Separator className="mx-1 data-[orientation=vertical]:h-4" orientation="vertical" /> : null}++ {hints.map(entry => (+ <FilterChip+ key={entry.value}+ label={tagCopy(vocabularyTag(entry.value), t.connectorsPage.vocabulary).label}+ onClick={() => set({ hint: filter.hint === entry.value ? null : entry.value })}+ selected={filter.hint === entry.value}+ />+ ))}++ {categories.length > 0 ? (+ <CategoryPicker categories={categories} onChange={category => set({ category })} value={filter.category} />+ ) : null}++ {quickActions.length > 0 ? (+ <div className="ml-auto flex items-center gap-1.5">+ {quickActions.map(action => (+ <Button+ aria-pressed={currentAction?.id === action.id}+ key={action.id}+ onClick={() => onApplyQuickAction(action.id)}+ size="xs"+ variant={currentAction?.id === action.id ? 'secondary' : 'outline'}+ >+ {quickActionLabel(copy, action.id)}+ </Button>+ ))}+ </div>+ ) : null}+ </div>+ )}+ </div>+ )+}++function FilterChip({+ count,+ label,+ onClick,+ selected+}: {+ count?: number+ label: string+ onClick: () => void+ selected: boolean+}) {+ return (+ <Button aria-pressed={selected} onClick={onClick} size="xs" variant={selected ? 'secondary' : 'ghost'}>+ {label}+ {count === undefined ? null : (+ <span className={cn('tabular-nums', selected ? 'opacity-70' : 'text-(--ui-text-quaternary)')}>{count}</span>+ )}+ </Button>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/tools-list.tsx b/apps/desktop/src/app/capabilities/connectors/tools-list.tsxnew file mode 100644index 00000000000..f4efc2d9c73--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/tools-list.tsx@@ -0,0 +1,543 @@+import type * as React from 'react'+import { type ReactNode, useCallback, useLayoutEffect, useMemo, useRef, useState } from 'react'++import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'++import {+ availableQuickActions,+ categoryCounts,+ deprecatedCount,+ EMPTY_TOOLS_FILTER,+ facetChips,+ facetSummary,+ filterTools,+ hintChips,+ isTinyConnector+} from './derive-tools'+import { TOOL_ROW_HEIGHT, ToolRow } from './tool-row'+import { ToolsFilterBar } from './tools-filter-bar'+import {+ isToolsStatusPhase,+ ToolsStatus,+ type ToolsStatusAction,+ type ToolsStatusPhase,+ ToolsWash+} from './tools-status'+import { ToolsSummary, useShowAllTools } from './tools-summary'+import type { ConflictDifference, QuickAction, ToolRowModel, ToolsEditorCounts, ToolsFilter } from './types'+import type { ToolsEditor } from './use-tools-editor'++const OVERSCAN = 4+const MIN_VIEWPORT = 200++const EMPTY_QUICK_ACTIONS: QuickAction[] = []++export interface ToolsListProps {+ appOff?: boolean+ conflict?: ConflictDifference+ connectorName: string+ editor: ToolsEditor+ listKey: string+ onReload: () => void+ onRemove?: () => void+ onRetry: () => void+ onRetryRules?: () => void+ onSignIn?: () => void+ preview?: boolean+ readOnly?: boolean+ rulesSignedOut?: boolean+ signedOut?: boolean+ summaryTitle?: string+ tools: ToolRowModel[]+}++export function ToolsList(props: ToolsListProps) {+ const phase = props.editor.phase++ if (phase === 'loading') {+ return <ToolsWash />+ }++ if (phase === 'unavailable') {+ return <UnavailableLine onRetry={props.onRetry} />+ }++ if (isToolsStatusPhase(phase)) {+ return (+ <StatusColumn+ connectorName={props.connectorName}+ difference={props.conflict ?? { theyOff: 0, theyOn: 0 }}+ editor={props.editor}+ onReload={props.onReload}+ onRemove={props.onRemove}+ onSignIn={props.onSignIn}+ phase={phase}+ />+ )+ }++ return <ToolsListBody {...props} />+}++function ToolsListBody(props: ToolsListProps) {+ const { t } = useI18n()+ const [filter, setFilter] = useState<ToolsFilter>(EMPTY_TOOLS_FILTER)++ const {+ appOff = false,+ connectorName,+ editor,+ listKey,+ onRetryRules,+ onSignIn,+ preview = false,+ readOnly = false,+ rulesSignedOut = false,+ signedOut = false,+ summaryTitle,+ tools+ } = props++ const frozen = readOnly || preview || appOff+ const all = useShowAllTools(listKey, editor.dirty)++ const chrome = useMemo(() => {+ const counted = filter.showDeprecated ? tools : tools.filter(tool => !tool.deprecated)++ return {+ categories: categoryCounts(counted),+ deprecated: deprecatedCount(tools),+ facets: facetChips(counted),+ hints: hintChips(counted),+ quickActions: availableQuickActions(tools),+ tiny: isTinyConnector(tools)+ }+ }, [filter.showDeprecated, tools])++ const visible = useMemo(() => filterTools(tools, filter), [tools, filter])+ const summary = useMemo(() => facetSummary(tools, editor.isOn), [tools, editor.isOn])++ return (+ <div className="flex min-h-0 flex-1 flex-col" data-slot="tools-list">+ {all.open ? (+ <ToolsFilterBar+ categories={chrome.categories}+ currentAction={editor.currentAction}+ facets={chrome.facets}+ filter={filter}+ hints={chrome.hints}+ onApplyQuickAction={editor.applyQuickAction}+ onFilterChange={setFilter}+ onShowSummary={all.hide}+ quickActions={frozen ? EMPTY_QUICK_ACTIONS : chrome.quickActions}+ tiny={chrome.tiny}+ total={tools.length}+ />+ ) : (+ <ToolsSummary+ connectorName={connectorName}+ onShowAll={all.show}+ onToggleFacet={editor.toggleFacet}+ preview={preview}+ readOnly={readOnly || appOff}+ rows={summary}+ title={summaryTitle}+ total={tools.length}+ />+ )}++ <FrozenLines+ appOffName={appOff ? connectorName : undefined}+ frozen={readOnly || appOff}+ onRetryRules={onRetryRules}+ onSignIn={onSignIn}+ preview={preview}+ rulesSignedOut={rulesSignedOut}+ signedOut={signedOut}+ />++ {all.open ? (+ <ToolViewport+ isOn={editor.isOn}+ label={t.connectorsPage.tools.toolList(connectorName)}+ onToggle={editor.toggle}+ preview={preview}+ readOnly={frozen}+ tools={visible}+ />+ ) : null}++ {all.open && chrome.deprecated > 0 ? (+ <DeprecatedToggle+ count={chrome.deprecated}+ onToggle={() => setFilter({ ...filter, showDeprecated: !filter.showDeprecated })}+ shown={filter.showDeprecated}+ />+ ) : null}++ {editor.dirty && !frozen ? (+ <DirtyFooter+ counts={editor.counts}+ onDiscard={editor.discard}+ onSave={() => void editor.save()}+ saving={editor.phase === 'saving'}+ />+ ) : null}+ </div>+ )+}++function StatusColumn({+ connectorName,+ difference,+ editor,+ onReload,+ onRemove,+ onSignIn,+ phase+}: {+ connectorName: string+ difference: ConflictDifference+ editor: ToolsEditor+ onReload: () => void+ onRemove?: () => void+ onSignIn?: () => void+ phase: ToolsStatusPhase+}) {+ const act = {+ keepMine: () => void editor.keepMine(),+ reload: () => {+ editor.discard()+ onReload()+ },+ remove: onRemove,+ signIn: onSignIn+ } satisfies Record<ToolsStatusAction, (() => void) | undefined>++ return (+ <ToolsStatus+ connectorName={connectorName}+ difference={difference}+ onAction={id => act[id]?.()}+ phase={phase}+ />+ )+}++function Line({ action, label }: { action?: ReactNode; label: string }) {+ return (+ <div className="flex shrink-0 items-center gap-2 border-b border-(--ui-stroke-tertiary) px-3.5 py-1.5">+ <span className="min-w-0 flex-1 text-[0.7rem] text-(--ui-text-tertiary)">{label}</span>+ {action}+ </div>+ )+}++function UnavailableLine({ onRetry }: { onRetry: () => void }) {+ const { t } = useI18n()++ return (+ <Line+ action={+ <Button onClick={onRetry} size="inline" variant="textStrong">+ {t.connectorsPage.tools.retry}+ </Button>+ }+ label={t.connectorsPage.tools.unavailableLine}+ />+ )+}++function SignInLine({ onSignIn }: { onSignIn: () => void }) {+ const { t } = useI18n()++ return (+ <Line+ action={+ <Button onClick={onSignIn} size="inline" variant="textStrong">+ {t.connectorsPage.page.signIn}+ </Button>+ }+ label={t.connectorsPage.tools.staleSignIn}+ />+ )+}++function FrozenLines({+ appOffName,+ frozen,+ onRetryRules,+ onSignIn,+ preview,+ rulesSignedOut,+ signedOut+}: {+ appOffName?: string+ frozen: boolean+ onRetryRules?: () => void+ onSignIn?: () => void+ preview: boolean+ rulesSignedOut: boolean+ signedOut: boolean+}) {+ return (+ <>+ {frozen && !preview ? (+ <RulesLine+ appOffName={appOffName}+ onRetryRules={onRetryRules}+ onSignIn={onSignIn}+ signedOut={rulesSignedOut}+ />+ ) : null}++ {signedOut && onSignIn ? <SignInLine onSignIn={onSignIn} /> : null}+ </>+ )+}++function RulesLine({+ appOffName,+ onRetryRules,+ onSignIn,+ signedOut+}: {+ appOffName?: string+ onRetryRules?: () => void+ onSignIn?: () => void+ signedOut: boolean+}) {+ const { t } = useI18n()+ const copy = t.connectorsPage++ if (appOffName) {+ return <Line label={copy.dialog.rulesAppOff(appOffName)} />+ }++ return (+ <Line+ action={+ signedOut && onSignIn ? (+ <Button onClick={onSignIn} size="inline" variant="textStrong">+ {copy.page.signIn}+ </Button>+ ) : onRetryRules ? (+ <Button onClick={onRetryRules} size="inline" variant="textStrong">+ {copy.page.retry}+ </Button>+ ) : null+ }+ label={signedOut ? copy.dialog.rulesSignIn : copy.dialog.rulesReadOnly}+ />+ )+}++function DeprecatedToggle({ count, onToggle, shown }: { count: number; onToggle: () => void; shown: boolean }) {+ const { t } = useI18n()+ const copy = t.connectorsPage.tools++ return (+ <div className="flex shrink-0 border-t border-(--ui-stroke-tertiary) px-3.5 py-1">+ <Button aria-pressed={shown} onClick={onToggle} size="xs" variant="text">+ {shown ? copy.hideDeprecated(count) : copy.showDeprecated(count)}+ </Button>+ </div>+ )+}++function ToolViewport({+ isOn,+ label,+ onToggle,+ preview,+ readOnly,+ tools+}: {+ isOn: (slug: string) => boolean+ label: string+ onToggle: (slug: string) => void+ preview: boolean+ readOnly: boolean+ tools: ToolRowModel[]+}) {+ const { t } = useI18n()+ const [scrollTop, setScrollTop] = useState(0)+ const [expanded, setExpanded] = useState<null | string>(null)+ const [detailHeight, setDetailHeight] = useState(0)+ const viewport = useViewportHeight()++ const measureDetail = useCallback((node: HTMLDivElement | null) => {+ if (node) {+ setDetailHeight(Math.max(0, node.getBoundingClientRect().height - TOOL_ROW_HEIGHT))+ }+ }, [])++ const expandedIndex = expanded === null ? -1 : tools.findIndex(tool => tool.slug === expanded)+ const extra = expandedIndex >= 0 ? detailHeight : 0+ const total = tools.length * TOOL_ROW_HEIGHT + extra+ const cut = expandedIndex >= 0 ? (expandedIndex + 1) * TOOL_ROW_HEIGHT : Number.POSITIVE_INFINITY++ const indexAt = (y: number) => Math.max(0, Math.floor((y < cut ? y : Math.max(cut, y - extra)) / TOOL_ROW_HEIGHT))++ const offsetAt = (index: number) =>+ index * TOOL_ROW_HEIGHT + (expandedIndex >= 0 && index > expandedIndex ? extra : 0)++ const top = Math.min(scrollTop, Math.max(0, total - viewport.height))++ const start = Math.max(0, indexAt(top) - OVERSCAN)+ const end = Math.min(tools.length, indexAt(top + viewport.height) + OVERSCAN + 1)++ const toggleExpanded = (slug: string) =>+ setExpanded(previous => {+ if (previous === slug) {+ setDetailHeight(0)++ return null+ }++ return slug+ })++ const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {+ const node = event.currentTarget+ const step = scrollStepFor(event.key, viewport.height)++ if (step === undefined || event.target !== node) {+ return+ }++ event.preventDefault()+ node.scrollTop = step === 'top' ? 0 : step === 'bottom' ? total : node.scrollTop + step+ }++ return (+ <div+ aria-label={label}+ className="min-h-0 flex-1 overflow-y-auto overscroll-contain [overflow-anchor:none] outline-none focus-visible:ring-[0.1875rem] focus-visible:ring-ring/50"+ data-slot="tools-viewport"+ onKeyDown={onKeyDown}+ onScroll={event => setScrollTop(event.currentTarget.scrollTop)}+ ref={viewport.ref}+ role="list"+ tabIndex={0}+ >+ {tools.length === 0 ? (+ <p className="px-3.5 py-8 text-center text-xs text-(--ui-text-tertiary)">{t.connectorsPage.tools.noMatch}</p>+ ) : null}++ <div className="relative" style={{ height: total }}>+ <div className="absolute inset-x-0" style={{ top: offsetAt(start) }}>+ {tools.slice(start, end).map((tool, offset) => (+ <div+ aria-posinset={start + offset + 1}+ aria-setsize={tools.length}+ key={tool.slug}+ ref={expanded === tool.slug ? measureDetail : undefined}+ role="listitem"+ >+ <ToolRow+ expanded={expanded === tool.slug}+ on={isOn(tool.slug)}+ onExpand={() => toggleExpanded(tool.slug)}+ onToggle={() => onToggle(tool.slug)}+ preview={preview}+ readOnly={readOnly}+ tool={tool}+ />+ </div>+ ))}+ </div>+ </div>+ </div>+ )+}++type ScrollStep = 'bottom' | 'top' | number++const SCROLL_KEYS = {+ ArrowDown: () => TOOL_ROW_HEIGHT,+ ArrowUp: () => -TOOL_ROW_HEIGHT,+ End: () => 'bottom',+ Home: () => 'top',+ PageDown: (viewport: number) => viewport,+ PageUp: (viewport: number) => -viewport+} satisfies Record<string, (viewport: number) => ScrollStep>++function scrollStepFor(key: string, viewport: number): ScrollStep | undefined {+ if (!Object.hasOwn(SCROLL_KEYS, key)) {+ return undefined+ }++ // SAFETY: guarded by `Object.hasOwn` on the line above.+ return SCROLL_KEYS[key as keyof typeof SCROLL_KEYS](viewport)+}++function useViewportHeight() {+ const ref = useRef<HTMLDivElement | null>(null)+ const [height, setHeight] = useState(MIN_VIEWPORT)++ const read = useCallback(() => {+ const node = ref.current++ if (node) {+ setHeight(previous => {+ const next = Math.max(MIN_VIEWPORT, Math.round(node.clientHeight))++ return previous === next ? previous : next+ })+ }+ }, [])++ useLayoutEffect(() => {+ read()++ const node = ref.current++ // oxlint-disable-next-line anti-slop/no-runtime-typeof -- SAFETY: an environment guard, not a value parse: `ResizeObserver` is absent in jsdom and in an Electron renderer before layout, and `typeof` is the only read that does not throw.+ if (!node || typeof ResizeObserver === 'undefined') {+ return+ }++ const observer = new ResizeObserver(read)++ observer.observe(node)++ return () => observer.disconnect()+ }, [read])++ return { height, ref }+}++function DirtyFooter({+ counts,+ onDiscard,+ onSave,+ saving+}: {+ counts: ToolsEditorCounts+ onDiscard: () => void+ onSave: () => void+ saving: boolean+}) {+ const { t } = useI18n()+ const copy = t.connectorsPage.tools++ return (+ <div+ className="flex shrink-0 items-center gap-2.5 border-t border-(--ui-stroke-tertiary) bg-(--ui-bg-chrome) px-3.5 py-2"+ data-slot="tools-dirty-footer"+ >+ <span aria-hidden className="size-1.5 shrink-0 rounded-full bg-(--theme-primary)" />+ <span className="min-w-0 flex-1 truncate text-xs text-(--ui-text-primary)">+ {copy.footerDirty(counts.off, counts.backOn)}+ </span>+ <Button disabled={saving} onClick={onDiscard} size="xs" variant="text">+ {copy.discard}+ </Button>+ <Button disabled={saving} loading={saving} onClick={onSave} size="xs">+ {saving ? copy.saving : copy.save}+ </Button>+ </div>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/tools-panel.tsx b/apps/desktop/src/app/capabilities/connectors/tools-panel.tsxnew file mode 100644index 00000000000..1fca895ffe8--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/tools-panel.tsx@@ -0,0 +1,157 @@+import { useMemo } from 'react'++import type { ProfileScope } from '@/hermes'+import { isToolEnabled } from '@/lib/mcp-tool-filter'++import { okProbe } from '../mcp/mcp-status'+import type { McpServersController } from '../mcp/use-mcp-servers'++import {+ type ConnectorPolicyView,+ connectorToolRows,+ memberDisabledTools,+ memberRevision,+ orgLockedTools+} from './data/join'+import { useConnectorToolsSave } from './data/mutations'+import type { ConnectorToolsView } from './data/queries'+import { localServerName } from './derive'+import { conflictDifference, toolDisplayName, toolRows } from './derive-tools'+import { ToolsList } from './tools-list'+import type { ConnectorCardModel, ToolInput } from './types'+import { type SaveResult, useToolsEditor } from './use-tools-editor'++export interface HostedToolsPanelProps {+ card: ConnectorCardModel+ disabledTools?: readonly string[]+ onDisconnect: () => void+ onRetryRules?: () => void+ onSignIn: () => void+ policy: ConnectorPolicyView+ readOnly?: boolean+ rulesSignedOut?: boolean+ scope: ProfileScope+ tools: ConnectorToolsView+}++export function HostedToolsPanel({+ card,+ disabledTools = [],+ onDisconnect,+ onRetryRules,+ onSignIn,+ policy,+ readOnly = false,+ rulesSignedOut = false,+ scope,+ tools+}: HostedToolsPanelProps) {+ const saver = useConnectorToolsSave(scope, card.slug, memberRevision(policy))++ const rows = useMemo(+ () =>+ readOnly ? toolRows(tools.tools, new Set(disabledTools)) : connectorToolRows(policy, card.slug, tools.tools),+ [card.slug, disabledTools, policy, readOnly, tools.tools]+ )++ const savedDisabled = useMemo(+ () => (readOnly ? [...disabledTools] : [...memberDisabledTools(policy, card.slug)]),+ [card.slug, disabledTools, policy, readOnly]+ )++ const editor = useToolsEditor({+ editorKey: card.slug,+ onSave: saver.onSave,+ savedDisabled,+ status: tools.status,+ tools: rows+ })++ return (+ <ToolsList+ appOff={card.state === 'off'}+ conflict={saver.theirs ? conflictDifference(saver.theirs, editor.local) : undefined}+ connectorName={card.name}+ editor={editor}+ listKey={card.slug}+ onReload={saver.reload}+ onRemove={onDisconnect}+ onRetry={tools.retry}+ onRetryRules={onRetryRules}+ onSignIn={onSignIn}+ preview={card.ways.hosted?.connected !== true}+ readOnly={readOnly}+ rulesSignedOut={rulesSignedOut}+ signedOut={tools.signedOut}+ tools={rows}+ />+ )+}++export interface LocalToolsPanelProps {+ card: ConnectorCardModel+ controller: McpServersController+ onRemove: () => void+}++export function LocalToolsPanel({ card, controller, onRemove }: LocalToolsPanelProps) {+ const name = localServerName(card)+ const probe = controller.probes[name]+ const entry = controller.servers[name]++ const status =+ card.ways.local?.serverEnabled === false+ ? 'off'+ : card.ways.local?.reason?.key === 'serverNeedsAuth'+ ? 'needsAuth'+ : !probe || probe === 'probing'+ ? 'loading'+ : probe.ok+ ? null+ : 'unavailable'++ const discovered = useMemo(() => okProbe(probe)?.tools.map(tool => tool.name) ?? [], [probe])++ const inputs = useMemo<ToolInput[]>(+ () =>+ okProbe(probe)?.tools.map(tool => ({+ categories: [],+ deprecated: false,+ description: tool.description ?? '',+ facet: 'unclassified',+ hints: [],+ name: toolDisplayName(tool.name),+ slug: tool.name+ })) ?? [],+ [probe]+ )++ const savedDisabled = useMemo(+ () => discovered.filter(tool => entry !== undefined && !isToolEnabled(entry, tool)),+ [discovered, entry]+ )++ const rows = useMemo(() => toolRows(inputs, new Set(savedDisabled)), [inputs, savedDisabled])++ const onSave = async (disabled: string[]): Promise<SaveResult> =>+ (await controller.setServerTools(name, disabled, discovered)) ? 'saved' : 'failed'++ const editor = useToolsEditor({ editorKey: name, onSave, savedDisabled, status, tools: rows })++ return (+ <ToolsList+ connectorName={card.name}+ editor={editor}+ listKey={name}+ onReload={() => void controller.runProbe(name)}+ onRemove={onRemove}+ onRetry={() => void controller.runProbe(name)}+ preview={card.state !== 'connected'}+ tools={rows}+ />+ )+}++export function orgDisabledCount(policy: ConnectorPolicyView, slug: string, tools: readonly ToolInput[]): number {+ return orgLockedTools(policy, slug, tools).size+}diff --git a/apps/desktop/src/app/capabilities/connectors/tools-status.tsx b/apps/desktop/src/app/capabilities/connectors/tools-status.tsxnew file mode 100644index 00000000000..61c9fbaac55--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/tools-status.tsx@@ -0,0 +1,120 @@+import { PanelEmpty } from '@/app/overlays/panel'+import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'+import type { Translations } from '@/i18n/types'++import type { ConflictDifference, ToolsEditorPhase } from './types'++export function ToolsWash({ label, rows = 8 }: { label?: string; rows?: number }) {+ const { t } = useI18n()++ return (+ <div aria-busy className="grid gap-2 px-3.5 py-3" role="status">+ <span className="sr-only">{label ?? t.connectorsPage.tools.loading}</span>+ {Array.from({ length: rows }, (_, index) => (+ <span+ aria-hidden+ className="h-3 rounded-sm bg-(--ui-bg-quaternary)"+ key={index}+ style={{ width: `${68 - (index % 4) * 9}%` }}+ />+ ))}+ </div>+ )+}++type PageCopy = Translations['connectorsPage']+type ToolsCopy = PageCopy['tools']++export type ToolsStatusAction = 'keepMine' | 'reload' | 'remove' | 'signIn'+export type ToolsStatusPhase = 'conflict' | 'gone' | 'needsAuth' | 'off' | 'signedOut'++interface StatusContext {+ connectorName: string+ difference: ConflictDifference+}++interface StatusView {+ actions: { id: ToolsStatusAction; label: (copy: PageCopy) => string; variant?: 'secondary' }[]+ body: (copy: ToolsCopy, context: StatusContext) => string+ icon: string+ title: (copy: ToolsCopy, context: StatusContext) => string+}++type StatusTable = { readonly [phase in ToolsStatusPhase]: StatusView }++const STATUS: StatusTable = {+ conflict: {+ actions: [+ { id: 'reload', label: copy => copy.tools.conflictReload, variant: 'secondary' },+ { id: 'keepMine', label: copy => copy.tools.conflictSave }+ ],+ body: (copy, { difference }) => copy.conflictBody(difference.theyOff, difference.theyOn),+ icon: 'git-merge',+ title: copy => copy.conflictTitle+ },+ gone: {+ actions: [{ id: 'remove', label: copy => copy.tools.remove, variant: 'secondary' }],+ body: copy => copy.goneBody,+ icon: 'circle-slash',+ title: (copy, { connectorName }) => copy.goneTitle(connectorName)+ },+ needsAuth: {+ actions: [],+ body: copy => copy.needsAuthBody,+ icon: 'key',+ title: (copy, { connectorName }) => copy.needsAuthTitle(connectorName)+ },+ off: {+ actions: [],+ body: copy => copy.offBody,+ icon: 'plug',+ title: (copy, { connectorName }) => copy.offTitle(connectorName)+ },+ signedOut: {+ actions: [{ id: 'signIn', label: copy => copy.page.signIn }],+ body: copy => copy.signedOutBody,+ icon: 'sign-in',+ title: copy => copy.signedOutTitle+ }+}++export function isToolsStatusPhase(phase: ToolsEditorPhase): phase is ToolsStatusPhase {+ return phase in STATUS+}++export function ToolsStatus({+ connectorName,+ difference,+ onAction,+ phase+}: {+ connectorName: string+ difference: ConflictDifference+ onAction: (id: ToolsStatusAction) => void+ phase: ToolsStatusPhase+}) {+ const { t } = useI18n()+ const copy = t.connectorsPage.tools+ const view = STATUS[phase]+ const context = { connectorName, difference }++ return (+ <PanelEmpty+ action={+ view.actions.length > 0 ? (+ <div className="flex items-center gap-2">+ {view.actions.map(action => (+ <Button key={action.id} onClick={() => onAction(action.id)} size="xs" variant={action.variant}>+ {action.label(t.connectorsPage)}+ </Button>+ ))}+ </div>+ ) : undefined+ }+ description={view.body(copy, context)}+ icon={view.icon}+ title={view.title(copy, context)}+ />+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/tools-summary.tsx b/apps/desktop/src/app/capabilities/connectors/tools-summary.tsxnew file mode 100644index 00000000000..03a3ba99f8c--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/tools-summary.tsx@@ -0,0 +1,127 @@+import { useCallback, useState } from 'react'++import { Button } from '@/components/ui/button'+import { Switch } from '@/components/ui/switch'+import { useI18n } from '@/i18n'+import type { Translations } from '@/i18n/types'++import { tagCopy, vocabularyTag } from './hint-vocabulary'+import type { FacetSummaryRow } from './types'++const OPENED = new Set<string>()++export function openToolsList(listKey: string): void {+ OPENED.add(listKey)+}++export function resetOpenedTools(): void {+ OPENED.clear()+}++export function useShowAllTools(key: string, forced: boolean) {+ const [choice, setChoice] = useState<null | { key: string; open: boolean }>(null)++ const show = useCallback(() => {+ OPENED.add(key)+ setChoice({ key, open: true })+ }, [key])++ const hide = useCallback(() => {+ OPENED.delete(key)+ setChoice({ key, open: false })+ }, [key])++ const chosen = choice?.key === key ? choice.open : null++ return { hide, open: forced || (chosen ?? OPENED.has(key)), show }+}++function onLabel(copy: Translations['connectorsPage']['tools'], row: FacetSummaryRow): string {+ if (row.switchState === 'on') {+ return copy.summaryAllOn+ }++ return row.switchState === 'off' ? copy.summaryOff : copy.summarySomeOn(row.on, row.total)+}++export interface ToolsSummaryProps {+ connectorName: string+ onShowAll: () => void+ onToggleFacet: (facet: string, on: boolean) => void+ preview: boolean+ readOnly: boolean+ rows: FacetSummaryRow[]+ title?: string+ total: number+}++export function ToolsSummary({+ connectorName,+ onShowAll,+ onToggleFacet,+ preview,+ readOnly,+ rows,+ title,+ total+}: ToolsSummaryProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage.tools++ return (+ <div className="grid min-h-0 flex-1 content-start gap-3 overflow-y-auto px-3.5 py-3" data-slot="tools-summary">+ <div className="flex items-baseline justify-between gap-3">+ <h3 className="min-w-0 truncate text-xs font-medium text-(--ui-text-primary)">+ {title ?? (preview ? copy.summaryPreviewTitle(connectorName) : copy.summaryTitle(connectorName))}+ </h3>+ <span className="shrink-0 tabular-nums text-[0.7rem] text-(--ui-text-tertiary)">+ {copy.summaryCount(total)}+ </span>+ </div>++ <ul className="grid">+ {rows.map(row => {+ const unclassed = row.facet === 'unclassified'+ const alone = unclassed && rows.length === 1++ const label = unclassed+ ? copy[alone ? 'summaryAllTools' : 'summaryOther']+ : tagCopy(vocabularyTag(row.facet), t.connectorsPage.vocabulary).label++ return (+ <li+ className="flex items-center gap-3 border-t border-(--ui-stroke-tertiary) py-2 first:border-t-0"+ key={row.facet}+ >+ <span className="min-w-0 flex-1 truncate text-[0.8125rem] font-medium text-(--ui-text-primary)">+ {label}+ </span>+ <span className="shrink-0 tabular-nums text-xs text-(--ui-text-secondary)">{row.total}</span>++ {preview ? null : (+ <>+ <span className="w-24 shrink-0 text-right text-[0.7rem] text-(--ui-text-tertiary)">+ {onLabel(copy, row)}+ </span>+ <Switch+ aria-label={alone ? copy.allToolsSwitch : copy.facetSwitch(label)}+ checked={row.switchState !== 'off'}+ disabled={readOnly || row.locked}+ onCheckedChange={next => onToggleFacet(row.facet, next)}+ size="xs"+ />+ </>+ )}+ </li>+ )+ })}+ </ul>++ <div className="flex items-center gap-3">+ <Button onClick={onShowAll} size="inline" variant="textStrong">+ {copy.showAllTools(total)}+ </Button>+ </div>+ </div>+ )+}diff --git a/apps/desktop/src/app/capabilities/connectors/types.ts b/apps/desktop/src/app/capabilities/connectors/types.tsnew file mode 100644index 00000000000..3eaeaaff3b7--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/types.ts@@ -0,0 +1,219 @@+export type ConnectorResidency = 'hosted' | 'local'++export type LocalServerStatus = 'error' | 'needs-auth' | 'off' | 'ok' | 'probing' | 'unknown'++export interface HostedConnectorInput {+ accountLabel?: string+ connected: boolean+ connectedAt?: string+ connectionStatus?: string+ description?: string+ disabledTools?: readonly string[]+ enabled: boolean+ inCatalog?: boolean+ orgLocked?: boolean+ slug: string+ statusReason?: string+ toolsOff?: number+}++export interface LocalServerInput {+ canAuthenticate?: boolean+ connectorSlug?: string+ description?: string+ enabled: boolean+ inCatalog?: boolean+ name: string+ plugin?: string+ status: LocalServerStatus+ target: string+ title?: string+ toolsOn?: number+ toolsTotal?: number+ unused?: boolean+}++export type ConnectorAuthType = 'apiKey' | 'none' | 'oauth'++export interface BundledEntryInput {+ authType: ConnectorAuthType+ connectorSlug?: string+ description?: string+ name: string+ needsEnv: boolean+}++export interface ToolInput {+ categories: string[]+ deprecated: boolean+ description: string+ facet: string+ hints: string[]+ name: string+ slug: string+}++export type ConnectorState = 'available' | 'broken' | 'connected' | 'connecting' | 'expired' | 'off' | 'unknown'++export type ConnectorOffBy = 'me' | 'org'++export type ConnectorStateWord =+ | 'accessExpired'+ | 'available'+ | 'connected'+ | 'connecting'+ | 'connectionUnknown'+ | 'couldNotConnect'+ | 'offByYourOrganisation'+ | 'offForYou'+ | 'serverConnecting'+ | 'serverError'+ | 'serverNeedsAuth'+ | 'serverOff'+ | 'serverOn'+ | 'serverOnUnused'++export type ConnectorFactKey = 'tools' | 'toolsOff' | 'toolsOn' | 'toolsSomeOn'++export interface ConnectorFact {+ count: number+ key: ConnectorFactKey+ on?: number+}++export interface ConnectorReason {+ key: 'finishSignIn' | 'reconnect' | 'serverError' | 'serverNeedsAuth'+ text?: string+}++export type ConnectorVerb =+ 'authenticate' | 'connect' | 'install' | 'openLogs' | 'reconnect' | 'stopWaiting' | 'tryAgain' | 'turnBackOn'++export interface ConnectorWayHosted {+ accountLabel?: string+ connected: boolean+ connectedAt?: string+ disabledTools?: readonly string[]+ fact?: ConnectorFact+ offBy?: ConnectorOffBy+ reason?: ConnectorReason+ state: ConnectorState+ verb?: ConnectorVerb+}++export interface ConnectorWayLocal {+ authType?: ConnectorAuthType+ entryName?: string+ fact?: ConnectorFact+ inCatalog?: boolean+ installed?: boolean+ needsEnv?: boolean+ plugin?: string+ reason?: ConnectorReason+ serverEnabled?: boolean+ serverName?: string+ state: ConnectorState+ target?: string+ unused?: boolean+ verb?: ConnectorVerb+}++export type ConnectorWays =+ { hosted: ConnectorWayHosted; local: ConnectorWayLocal | null } | { hosted: null; local: ConnectorWayLocal }++export interface ConnectorCardModel {+ description?: string+ fact?: ConnectorFact+ inCatalog: boolean+ name: string+ offBy?: ConnectorOffBy+ plugin?: string+ reason?: ConnectorReason+ residency: ConnectorResidency+ slug: string+ state: ConnectorState+ stateWord: ConnectorStateWord+ verb?: ConnectorVerb+ ways: ConnectorWays+}++export type ConnectorGroupId = 'available' | 'connected' | 'local' | 'off'++export interface ConnectorGroupModel {+ cards: ConnectorCardModel[]+ id: ConnectorGroupId+}++export type ConnectorSegmentId = 'all' | ConnectorGroupId++export interface ConnectorSegmentModel {+ count: number+ id: ConnectorSegmentId+}++export interface ConnectorsFilter {+ query: string+ segment: ConnectorSegmentId+}++export interface ConnectorPageModel {+ groups: ConnectorGroupModel[]+ hiddenMatches: number+ segment: ConnectorSegmentId+ segments: ConnectorSegmentModel[]+}++export type HostedPhase = 'failed' | 'loading' | 'ready' | 'signedOut' | 'unavailable'++export interface ToolRowModel {+ categories: string[]+ deprecated: boolean+ description: string+ facet: string+ hints: string[]+ lockedBy: 'org' | null+ name: string+ on: boolean+ slug: string+}++export interface ToolsFilter {+ category: null | string+ facet: null | string+ hint: null | string+ query: string+ showDeprecated: boolean+}++export type ToolsEditorPhase =+ 'conflict' | 'gone' | 'loading' | 'needsAuth' | 'off' | 'ready' | 'saving' | 'signedOut' | 'unavailable'++export type ToolsEditorStatus = Extract<+ ToolsEditorPhase,+ 'gone' | 'loading' | 'needsAuth' | 'off' | 'signedOut' | 'unavailable'+>++export interface FacetSummaryRow {+ facet: string+ locked: boolean+ on: number+ switchState: 'mixed' | 'off' | 'on'+ total: number+}++export interface ToolsEditorCounts {+ backOn: number+ off: number+}++export type QuickActionId = 'everything-on' | 'no-destructive' | 'read-only'++export interface QuickAction {+ facets: readonly string[]+ id: QuickActionId+}++export interface ConflictDifference {+ theyOn: number+ theyOff: number+}diff --git a/apps/desktop/src/app/capabilities/connectors/use-tools-editor.ts b/apps/desktop/src/app/capabilities/connectors/use-tools-editor.tsnew file mode 100644index 00000000000..8f80934559c--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/use-tools-editor.ts@@ -0,0 +1,176 @@+import { useCallback, useEffect, useMemo, useState } from 'react'++import {+ editorCounts,+ expandQuickAction,+ facetTools,+ isUntouchedByQuickActions,+ matchingQuickAction,+ quickActionById,+ sameSet+} from './derive-tools'+import type {+ QuickAction,+ QuickActionId,+ ToolRowModel,+ ToolsEditorCounts,+ ToolsEditorPhase,+ ToolsEditorStatus+} from './types'++export type SaveResult = 'conflict' | 'failed' | 'saved'++export interface SaveOptions {+ overwrite: boolean+}++export interface UseToolsEditorOptions {+ editorKey?: string+ onSave: (disabled: string[], options: SaveOptions) => Promise<SaveResult>+ savedDisabled: readonly string[]+ status?: ToolsEditorStatus | null+ tools: readonly ToolRowModel[]+}++export interface ToolsEditor {+ applyQuickAction: (id: QuickActionId) => void+ counts: ToolsEditorCounts+ currentAction: QuickAction | null+ dirty: boolean+ discard: () => void+ isOn: (slug: string) => boolean+ keepMine: () => Promise<SaveResult>+ local: string[]+ phase: ToolsEditorPhase+ save: () => Promise<SaveResult>+ toggle: (slug: string) => void+ toggleFacet: (facet: string, on: boolean) => void+}++export function useToolsEditor({+ editorKey,+ onSave,+ savedDisabled,+ status,+ tools+}: UseToolsEditorOptions): ToolsEditor {+ const [local, setLocal] = useState<string[]>([...savedDisabled])+ const [baseline, setBaseline] = useState<string[]>([...savedDisabled])+ const [editing, setEditing] = useState<'conflict' | 'ready' | 'saving'>('ready')+ const [pressed, setPressed] = useState<QuickActionId | null>(null)+ const [overwrite, setOverwrite] = useState(false)++ const savedKey = `${editorKey ?? ''}\u0000${[...savedDisabled].sort().join('\u0000')}`++ useEffect(() => {+ setLocal([...savedDisabled])+ setBaseline([...savedDisabled])+ setEditing('ready')+ setPressed(null)+ setOverwrite(false)+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [savedKey])++ const byslug = useMemo(() => new Map(tools.map(tool => [tool.slug, tool])), [tools])+ const disabledSet = useMemo(() => new Set(local), [local])+ const dirty = !sameSet(local, baseline)+ const counts = useMemo(() => editorCounts(local, baseline), [local, baseline])+ const currentAction = useMemo(() => matchingQuickAction(local, tools, pressed), [local, tools, pressed])++ const toggle = useCallback(+ (slug: string) => {+ if (byslug.get(slug)?.lockedBy) {+ return+ }++ setPressed(null)+ setLocal(previous => (previous.includes(slug) ? previous.filter(s => s !== slug) : [...previous, slug]))+ },+ [byslug]+ )++ const toggleFacet = useCallback(+ (facet: string, on: boolean) => {+ const slugs = facetTools(tools, facet)++ setPressed(null)+ setLocal(previous => {+ const without = previous.filter(slug => !slugs.includes(slug))++ return on ? without : [...without, ...slugs]+ })+ },+ [tools]+ )++ const applyQuickAction = useCallback(+ (id: QuickActionId) => {+ const action = quickActionById(id)++ setPressed(id)+ setLocal(previous => {+ const kept = previous.filter(slug => {+ const tool = byslug.get(slug)++ return tool !== undefined && (isUntouchedByQuickActions(tool) || tool.lockedBy !== null)+ })++ return [...new Set([...kept, ...expandQuickAction(action, tools)])]+ })+ },+ [byslug, tools]+ )++ const discard = useCallback(() => {+ setLocal(baseline)+ setEditing('ready')+ setPressed(null)+ setOverwrite(false)+ }, [baseline])++ const write = useCallback(+ async (asOverwrite: boolean) => {+ setEditing('saving')++ const result = await onSave(local, { overwrite: asOverwrite })++ setEditing(result === 'conflict' ? 'conflict' : 'ready')++ if (result === 'saved') {+ setBaseline(local)+ setOverwrite(false)+ }++ return result+ },+ [local, onSave]+ )++ const keepMine = useCallback(() => {+ setOverwrite(true)++ return write(true)+ }, [write])++ const save = useCallback(() => write(overwrite), [overwrite, write])++ const isOn = useCallback(+ (slug: string) => byslug.get(slug)?.lockedBy === null && !disabledSet.has(slug),+ [byslug, disabledSet]+ )++ return {+ applyQuickAction,+ counts,+ currentAction,+ dirty,+ discard,+ isOn,+ keepMine,+ local,+ phase: status ?? editing,+ save,+ toggle,+ toggleFacet+ }+}diff --git a/apps/desktop/src/app/capabilities/connectors/ways-section.tsx b/apps/desktop/src/app/capabilities/connectors/ways-section.tsxnew file mode 100644index 00000000000..314d88649d8--- /dev/null+++ b/apps/desktop/src/app/capabilities/connectors/ways-section.tsx@@ -0,0 +1,148 @@+import { type ReactNode } from 'react'++import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'++import { bothWaysOn, hostedStateWord } from './derive'+import { type InstallField, LocalInstall, LocalServerControl } from './local-server-control'+import type { ConnectorCardModel, ConnectorWayHosted, ConnectorWayLocal } from './types'++export interface WaysSectionProps {+ card: ConnectorCardModel+ hostedVerb?: boolean+ installFields?: readonly InstallField[]+ installing?: boolean+ onAuthenticate?: () => void+ onConnect?: () => void+ onDisconnect?: () => void+ onInstall?: (env: Record<string, string>) => void+ onReconnect?: () => void+ onServerToggle?: (next: boolean) => void+}++export function WaysSection({ card, ...rest }: WaysSectionProps) {+ const { t } = useI18n()+ const copy = t.connectorsPage.dialog+ const { hosted, local } = card.ways++ if (!hosted || !local) {+ return null+ }++ return (+ <section className="grid gap-2.5">+ <h3 className="text-xs font-medium text-(--ui-text-primary)">{copy.waysTitle(card.name)}</h3>++ <HostedWay+ onConnect={rest.hostedVerb === false ? undefined : rest.onConnect}+ onDisconnect={rest.hostedVerb === false ? undefined : rest.onDisconnect}+ onReconnect={rest.hostedVerb === false ? undefined : rest.onReconnect}+ quiet={local.installed === true && local.verb === 'authenticate'}+ way={hosted}+ />++ <LocalWay+ installFields={rest.installFields}+ installing={rest.installing}+ name={card.name}+ onAuthenticate={rest.onAuthenticate}+ onInstall={rest.onInstall}+ onServerToggle={rest.onServerToggle}+ way={local}+ />++ {bothWaysOn(card.ways) && rest.onServerToggle ? (+ <div className="grid justify-items-start gap-1">+ <p className="text-[0.7rem] text-(--ui-text-secondary)">{copy.bothOn(card.name)}</p>+ <Button onClick={() => rest.onServerToggle?.(false)} size="inline" variant="textStrong">+ {copy.turnOffLocal}+ </Button>+ </div>+ ) : null}+ </section>+ )+}++function WayRow({ children, title }: { children: ReactNode; title: string }) {+ return (+ <div className="grid gap-1.5 border-t border-(--ui-stroke-tertiary) pt-2">+ <span className="text-[0.72rem] font-medium text-(--ui-text-primary)">{title}</span>+ {children}+ </div>+ )+}++function HostedWay({+ onConnect,+ onDisconnect,+ onReconnect,+ quiet = false,+ way+}: {+ onConnect?: () => void+ onDisconnect?: () => void+ onReconnect?: () => void+ quiet?: boolean+ way: ConnectorWayHosted+}) {+ const { t } = useI18n()+ const copy = t.connectorsPage++ return (+ <WayRow title={copy.dialog.wayHosted}>+ <div className="flex flex-wrap items-center gap-2">+ <span className="min-w-0 flex-1 truncate text-[0.7rem] text-(--ui-text-tertiary)">+ {copy.card.state[hostedStateWord(way)]}+ </span>++ {way.state === 'available' && onConnect ? (+ <Button onClick={onConnect} size="xs" variant={quiet ? 'outline' : undefined}>+ {copy.card.verb.connect}+ </Button>+ ) : null}++ {(way.state === 'expired' || way.state === 'broken') && onReconnect ? (+ <Button onClick={onReconnect} size="xs" variant="secondary">+ {copy.card.verb.reconnect}+ </Button>+ ) : null}++ {way.state === 'connected' && onDisconnect ? (+ <Button className="text-destructive hover:text-destructive" onClick={onDisconnect} size="xs" variant="text">+ {copy.dialog.disconnect}+ </Button>+ ) : null}+ </div>+ </WayRow>+ )+}++function LocalWay({+ installFields = [],+ installing = false,+ name,+ onAuthenticate,+ onInstall,+ onServerToggle,+ way+}: {+ installFields?: readonly InstallField[]+ installing?: boolean+ name: string+ onAuthenticate?: () => void+ onInstall?: (env: Record<string, string>) => void+ onServerToggle?: (next: boolean) => void+ way: ConnectorWayLocal+}) {+ const { t } = useI18n()++ return (+ <WayRow title={t.connectorsPage.residencyLocal}>+ {way.installed === true || onInstall === undefined ? (+ <LocalServerControl name={name} onAuthenticate={onAuthenticate} onServerToggle={onServerToggle} way={way} />+ ) : (+ <LocalInstall installFields={installFields} installing={installing} onInstall={onInstall} />+ )}+ </WayRow>+ )+}diff --git a/apps/desktop/src/app/capabilities/index.tsx b/apps/desktop/src/app/capabilities/index.tsxindex f1c8088c08d..1b29d2af91b 100644--- a/apps/desktop/src/app/capabilities/index.tsx+++ b/apps/desktop/src/app/capabilities/index.tsx@@ -16,7 +16,7 @@ import { PanelEmpty } from '../overlays/panel'import { PageSearchShell } from '../page-search-shell'import type { SetStatusbarItemGroup } from '../shell/statusbar-controls'-import { McpTab } from './mcp/mcp-tab'+import { ConnectorsTab } from './connectors/connectors-tab'import { PluginsTab } from './plugins/plugins-tab'import { CapabilityScopeSelector, useCapabilityScope } from './scope-selector'import { EmbeddedHubPicker } from './skills/embedded-hub-picker'@@ -28,7 +28,7 @@ import { ToolsetsTab } from './toolsets/toolsets-tab'// Skills Hub browsing lives inside the Skills tab. Legacy `?tab=hub`// links fall back to 'skills' via useRouteEnumParam.-const CAPABILITY_MODES = ['skills', 'toolsets', 'mcp', 'plugins'] as const+const CAPABILITY_MODES = ['skills', 'toolsets', 'connectors', 'plugins'] as consttype CapabilityMode = (typeof CAPABILITY_MODES)[number]@@ -68,9 +68,7 @@ export function CapabilitiesView({const routeTab = useRouteEnumParam('tab', CAPABILITY_MODES, 'skills')const localTab = useState<CapabilityMode>('skills')const [mode, setMode] = embedded ? localTab : routeTab- // $gateway only feeds the MCP tab — gate the subscription so Skills/Toolsets- // tabs don't re-render on connect/disconnect/reconnect.- const gateway = useStoreSelector($gateway, g => (mode === 'mcp' ? g : null))+ const gateway = useStoreSelector($gateway, g => (mode === 'connectors' ? g : null))const [query, setQuery] = useState('')@@ -136,16 +134,16 @@ export function CapabilitiesView({<PageLoader label={t.skills.loading} />)- // One entry per tab. Each is keyed on the scope so switching profile or- // connection is a fresh tab — never one profile's selection, open editor or- // pending install left standing over another profile's backend.const tabContent = {// The gateway instance backs ONLY the live `reload.mcp` RPC, and it is the// ACTIVE gateway's socket — for a scope pinned to a different backend that- // RPC would hot-reload the wrong machine's MCP servers, so it is withheld// (config edits still apply on that backend's next session).- mcp: () => (- <McpTab gateway={scope.crossBackend ? null : gateway} key={`mcp-${scope.key}`} profile={scope.profile} />+ connectors: () => (+ <ConnectorsTab+ gateway={scope.crossBackend ? null : gateway}+ key={`connectors-${scope.key}`}+ profile={scope.profile}+ />),// Agent plugins for the scoped profile (selector in the section header),// app-level desktop plugins, and the docs catalog picker underneath.@@ -177,22 +175,19 @@ export function CapabilitiesView({activeTab={mode}onSearchChange={setQuery}onTabChange={id => setMode(id as CapabilityMode)}- // MCP manages a handful of entries with the editor right there —- // searching it is noise.- searchHidden={mode === 'mcp' || mode === 'plugins'}+ // The Connectors directory owns its search field; plugins has its own list.+ searchHidden={mode === 'connectors' || mode === 'plugins'}searchHints={searchHints}searchPlaceholder={mode === 'skills' ? t.skills.searchSkills : t.skills.searchToolsets}searchValue={query}tabs={[{ id: 'skills', label: t.skills.tabSkills, meta: skills?.length ?? null },{ id: 'toolsets', label: t.skills.tabToolsets, meta: toolsets ? visibleToolsetCount(toolsets) : null },- { id: 'mcp', label: t.skills.tabMcp },+ { id: 'connectors', label: t.connectorsPage.title },{ id: 'plugins', label: t.skills.tabPlugins }]}>- {/* One shared column: the scope selector sits above whichever tab is- active, so Skills / Tools / MCP all read and write the SAME selected- profile. */}+<div className="flex h-full flex-col">{mode !== 'plugins' && <CapabilityScopeSelector scope={scope} />}<div className="flex min-h-0 flex-1 flex-col">diff --git a/apps/desktop/src/app/capabilities/mcp/install-catalog-entry.ts b/apps/desktop/src/app/capabilities/mcp/install-catalog-entry.tsnew file mode 100644index 00000000000..36c1ca936e1--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/install-catalog-entry.ts@@ -0,0 +1,36 @@+import { getActionStatus, installMcpCatalogEntry, type McpCatalogEntry, type ProfileScope } from '@/hermes'+import { translateNow } from '@/i18n'++const INSTALL_POLL_MS = 1500++const INSTALL_DEADLINE_MS = 10 * 60_000++export async function installBundledEntry(+ entry: McpCatalogEntry,+ env: Record<string, string>,+ profile?: ProfileScope+): Promise<void> {+ const result = await installMcpCatalogEntry(entry.name, env, profile ?? undefined)++ if (!result.background || !result.action) {+ return+ }++ const deadline = Date.now() + INSTALL_DEADLINE_MS++ while (Date.now() < deadline) {+ const status = await getActionStatus(result.action, 1, profile ?? undefined)++ if (!status.running) {+ if (status.exit_code !== 0) {+ throw new Error(translateNow('settings.mcp.catalogInstallFailed', entry.name))+ }++ return+ }++ await new Promise(resolve => setTimeout(resolve, INSTALL_POLL_MS))+ }++ throw new Error(translateNow('settings.mcp.catalogInstallTimeout', entry.name))+}diff --git a/apps/desktop/src/app/capabilities/mcp/mcp-avatar.tsx b/apps/desktop/src/app/capabilities/mcp/mcp-avatar.tsxnew file mode 100644index 00000000000..9706a6930d8--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/mcp-avatar.tsx@@ -0,0 +1,25 @@++import { AvatarChip } from '@/components/ui/avatar-chip'+import { brandFor } from '@/lib/mcp-brands'+import { cn } from '@/lib/utils'++import { type ServerStatus, STATUS_DOT } from './mcp-status'++export function McpAvatar({ className, name, status }: { className?: string; name: string; status: ServerStatus }) {+ return (+ <AvatarChip+ brand={brandFor(name)}+ className={className}+ name={name}+ overlay={+ <span+ aria-hidden+ className={cn(+ 'absolute -bottom-0.5 -right-0.5 size-2 rounded-full ring-2 ring-(--ui-chat-surface-background)',+ STATUS_DOT[status]+ )}+ />+ }+ />+ )+}diff --git a/apps/desktop/src/app/capabilities/mcp/mcp-doc.ts b/apps/desktop/src/app/capabilities/mcp/mcp-doc.tsnew file mode 100644index 00000000000..4f006b46bbc--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/mcp-doc.ts@@ -0,0 +1,199 @@++// oxlint-disable-next-line anti-slop/no-shape-in-symbol-names -- `isServerShape` is main's exported name, shared with mcp-tab.tsx; it is bound to a domain name here instead of renaming the export.+import { type McpServerEntry, type McpServers, isServerShape as namesAServer, normalizeEntry } from '@/lib/mcp-servers'++export const STARTER_ENTRY = { command: 'npx', args: ['-y', '@modelcontextprotocol/server-filesystem', '/path/to/dir'] }++export const wrapDoc = (entries: McpServers) => JSON.stringify({ mcpServers: entries }, null, 2)++export function parseServersDoc(raw: string): McpServers {+ const parsed: unknown = JSON.parse(raw)++ if (!(parsed instanceof Object) || Array.isArray(parsed)) {+ throw new Error('Expected a JSON object')+ }++ // SAFETY: an object and not an array, checked on the line above; every property read below is optional.+ const doc = parsed as McpServerEntry++ if (namesAServer(doc)) {+ throw new Error('Wrap the server in {"mcpServers": {"name": …}} so it has a name')+ }++ const wrapper = doc.mcpServers ?? doc.mcp_servers++ // SAFETY: an object and not an array; `normalizeEntry` runs over every value below, so a non-object entry cannot reach a reader.+ const map = (wrapper instanceof Object && !Array.isArray(wrapper) ? wrapper : doc) as McpServers++ return Object.fromEntries(Object.entries(map).map(([name, entry]) => [name, normalizeEntry(entry)]))+}++export const serverEnabled = (server: McpServerEntry) => server.enabled !== false++export function withEnabled(server: McpServerEntry, enabled: boolean): McpServerEntry {+ const next = { ...server }++ if (enabled) {+ delete next.enabled+ } else {+ next.enabled = false+ }++ return next+}++export function uniqueServerKey(taken: McpServers, name: string): string {+ let key = name++ for (let i = 2; key in taken; i++) {+ key = `${name}-${i}`+ }++ return key+}++// ---------------------------------------------------------------------------+// Cursor → server-block mapping. A tolerant character walker (not JSON.parse —+// it must work mid-edit) that finds each server's key+object range inside the+// mcpServers container, so the editor cursor selects a server and the block+// can be highlighted.+// ---------------------------------------------------------------------------++export interface ServerBlock {+ from: number+ name: string+ to: number+}++function skipString(text: string, index: number): number {+ let i = index + 1++ while (i < text.length) {+ if (text[i] === '\\') {+ i += 2+ } else if (text[i] === '"') {+ return i + 1+ } else {+ i+++ }+ }++ return i+}++// Container: the object after "mcpServers"/"mcp_servers", else the doc root.+function containerStart(text: string): number {+ const wrapper = /"mcpServers"|"mcp_servers"/.exec(text)++ if (!wrapper) {+ return text.indexOf('{')+ }++ let i = wrapper.index + wrapper[0].length++ while (i < text.length && text[i] !== '{') {+ i+++ }++ return i+}++/** The index just past the `{…}` that starts at `index`, balancing braces and skipping strings. */+function objectEnd(text: string, index: number): number {+ let depth = 0+ let i = index++ while (i < text.length) {+ const c = text[i]++ if (c === '"') {+ i = skipString(text, i)++ continue+ }++ if (c === '{') {+ depth+++ } else if (c === '}') {+ depth--++ if (depth === 0) {+ return i + 1+ }+ }++ i+++ }++ return i+}++/** The index of the next sibling key after a non-object value. */+function siblingStart(text: string, index: number): number {+ let i = index++ while (i < text.length && text[i] !== ',' && text[i] !== '}') {+ if (text[i] === '"') {+ i = skipString(text, i)++ continue+ }++ i+++ }++ return i+}++/** The index of the value after the `:` that follows the key ending at `index`. */+function valueStart(text: string, index: number): number {+ let i = index++ while (i < text.length && text[i] !== ':') {+ i+++ }++ i++++ while (i < text.length && /\s/.test(text[i])) {+ i+++ }++ return i+}++export function scanServerBlocks(text: string): ServerBlock[] {+ const start = containerStart(text)++ if (start < 0 || text[start] !== '{') {+ return []+ }++ const blocks: ServerBlock[] = []+ let i = start + 1++ while (i < text.length && text[i] !== '}') {+ if (text[i] !== '"') {+ i++++ continue+ }++ const keyStart = i+ const keyEnd = skipString(text, i)+ const name = text.slice(keyStart + 1, keyEnd - 1)++ i = valueStart(text, keyEnd)++ if (text[i] === '{') {+ const to = objectEnd(text, i)++ blocks.push({ from: keyStart, name, to })+ i = to+ } else {+ i = siblingStart(text, i)+ }+ }++ return blocks+}diff --git a/apps/desktop/src/app/capabilities/mcp/mcp-editor.tsx b/apps/desktop/src/app/capabilities/mcp/mcp-editor.tsxnew file mode 100644index 00000000000..1395d8d8925--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/mcp-editor.tsx@@ -0,0 +1,98 @@+import { useState } from 'react'++import { JsonDocumentEditor } from '@/components/chat/json-document-editor'+import { Button } from '@/components/ui/button'+import { TextTab } from '@/components/ui/text-tab'+import { useI18n } from '@/i18n'+import { notifyError } from '@/store/notifications'++import { DetailPane } from '../../master-detail'++import { McpLogs, type McpLogSource } from './mcp-logs'+import type { McpServersController } from './use-mcp-servers'++export interface McpJsonEditorProps {+ controller: McpServersController+ highlightServer?: null | string+}++export function McpJsonEditor({ controller, highlightServer }: McpJsonEditorProps) {+ const { t } = useI18n()+ const m = t.settings.mcp++ const block =+ highlightServer === undefined+ ? controller.activeBlock+ : (controller.blocks.find(candidate => candidate.name === highlightServer) ?? null)++ return (+ <JsonDocumentEditor+ apiRef={controller.editorApi}+ disabled={controller.saving}+ filePath="mcp.json"+ header={+ <>+ mcp.json+ {controller.dirty && <span aria-hidden className="size-1.5 rounded-full bg-current/60" />}+ </>+ }+ highlight={block ? { from: block.from, to: block.to } : null}+ initialValue={controller.draft}+ onChange={controller.setDraft}+ onCursorChange={controller.setCursor}+ onFormatJsonError={error => notifyError(new Error(error), m.invalidJson)}+ onSave={() => void controller.saveDoc()}+ remountKey={controller.docVersion}+ trailing={+ <Button disabled={controller.saving || !controller.dirty} onClick={() => void controller.saveDoc()} size="xs">+ {controller.saving ? t.common.saving : t.common.save}+ </Button>+ }+ />+ )+}++export interface McpLogPaneProps {+ server: null | string+}++export function McpLogPane({ server }: McpLogPaneProps) {+ const { t } = useI18n()+ const m = t.settings.mcp+ const [source, setSource] = useState<McpLogSource>('stdio')++ return (+ <DetailPane+ actions={+ <span className="flex items-center gap-1.5">+ {(['stdio', 'agent'] as const).map(kind => (+ <TextTab+ active={source === kind}+ className="h-5 px-0.5 text-[0.65rem]"+ key={kind}+ onClick={() => setSource(kind)}+ >+ {kind}+ </TextTab>+ ))}+ </span>+ }+ defaultHeight={176}+ id="mcp-logs"+ title={<span className="text-[0.68rem] font-normal text-muted-foreground/60">{server ?? m.allServers}</span>}+ >+ <McpLogs emptyLabel={m.noOutput} server={server} source={source} />+ </DetailPane>+ )+}++export function McpEditorPane({ controller }: { controller: McpServersController }) {+ const saved = controller.selected !== null && controller.servers[controller.selected] !== undefined++ return (+ <main className="flex min-h-0 flex-col overflow-hidden">+ <McpJsonEditor controller={controller} />+ <McpLogPane server={saved ? controller.selected : null} />+ </main>+ )+}diff --git a/apps/desktop/src/app/capabilities/mcp/mcp-logs.tsx b/apps/desktop/src/app/capabilities/mcp/mcp-logs.tsxnew file mode 100644index 00000000000..eea2387a760--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/mcp-logs.tsx@@ -0,0 +1,65 @@++import { useStore } from '@nanostores/react'+import { useEffect, useState } from 'react'++import { LogTail } from '@/components/chat/log-tail'+import { getLogs } from '@/hermes'+import { startCompletionPoll } from '@/lib/completion-poll'+import { $activeGatewayProfile } from '@/store/profile'++export const LOG_POLL_MS = 2000++const STDIO_MARKER_RE = /^===== \[.*\] starting MCP server '(.+)' =====$/++export function filterStdioSections(lines: string[], server: string): string[] {+ const out: string[] = []+ let inSection = false++ for (const line of lines) {+ const marker = STDIO_MARKER_RE.exec(line.trim())++ if (marker) {+ inSection = marker[1] === server+ }++ if (inSection) {+ out.push(line)+ }+ }++ return out+}++export type McpLogSource = 'agent' | 'stdio'++export function McpLogs({+ emptyLabel,+ server,+ source+}: {+ emptyLabel: string+ server: null | string+ source: McpLogSource+}) {+ const [lines, setLines] = useState<null | string[]>(null)+ const activeProfile = useStore($activeGatewayProfile)++ useEffect(() => {+ setLines(null)++ return startCompletionPoll({+ delayMs: LOG_POLL_MS,+ poll: async () => {+ const response =+ source === 'stdio'+ ? await getLogs({ file: 'mcp', lines: 500 })+ : await getLogs({ file: 'agent', lines: 300, search: server ?? 'mcp' })++ return source === 'stdio' && server ? filterStdioSections(response.lines, server) : response.lines+ },+ publish: setLines+ })+ }, [server, source, activeProfile])++ return <LogTail emptyLabel={emptyLabel} lines={lines} />+}diff --git a/apps/desktop/src/app/capabilities/mcp/mcp-status.ts b/apps/desktop/src/app/capabilities/mcp/mcp-status.tsnew file mode 100644index 00000000000..5ea2535ffdb--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/mcp-status.ts@@ -0,0 +1,160 @@++import { compactNumber } from '@hermes/shared'++import { getUsageAnalytics, type McpTestResult, type ProfileScope } from '@/hermes'+import type { Translations } from '@/i18n'+import { estimateServerTokens, serverUsageCount } from '@/lib/mcp-cost'+import { NEEDS_AUTH_RE } from '@/lib/mcp-probe-cache'+import type { McpServerEntry } from '@/lib/mcp-servers'+import { countEnabledTools } from '@/lib/mcp-tool-filter'++import { serverEnabled } from './mcp-doc'++export const MCP_CATALOG_KEY = ['mcp-catalog'] as const++export type Probe = McpTestResult | 'probing'++export type ServerStatus = 'error' | 'needs-auth' | 'off' | 'ok' | 'probing' | 'unknown'++export const okProbe = (probe: Probe | undefined): McpTestResult | null =>+ probe && probe !== 'probing' && probe.ok ? probe : null++export interface ServerCost {+ tokens: null | number+ uses: null | number+}++export const MCP_USAGE_TTL_MS = 10 * 60_000+const mcpUsageCache = new Map<string, { at: number; value: Record<string, number> }>()++export async function loadMcpUsage(+ scopeKey: string,+ scopeProfile: ProfileScope+): Promise<null | Record<string, number>> {+ const cached = mcpUsageCache.get(scopeKey)++ if (cached && Date.now() - cached.at < MCP_USAGE_TTL_MS) {+ return cached.value+ }++ try {+ const analytics = await getUsageAnalytics(30, scopeProfile)+ const value = Object.fromEntries((analytics.tools ?? []).map(entry => [entry.tool, entry.count]))+ mcpUsageCache.set(scopeKey, { at: Date.now(), value })++ return value+ } catch {+ return null+ }+}++export function statusOf(server: McpServerEntry, probe: Probe | undefined): ServerStatus {+ if (!serverEnabled(server)) {+ return 'off'+ }++ if (probe === 'probing') {+ return 'probing'+ }++ if (!probe) {+ return 'unknown'+ }++ if (probe.ok) {+ return 'ok'+ }++ return NEEDS_AUTH_RE.test(probe.error ?? '') ? 'needs-auth' : 'error'+}++export const STATUS_DOT = {+ ok: 'bg-emerald-500',+ error: 'bg-red-500',+ 'needs-auth': 'bg-amber-500',+ probing: 'animate-pulse bg-foreground/40',+ off: 'bg-foreground/20',+ unknown: 'bg-foreground/20'+} satisfies Record<ServerStatus, string>++export function canAuthenticate(server: McpServerEntry, status: ServerStatus): boolean {+ const hasHeaderAuth = server.headers instanceof Object++ return (+ // oxlint-disable-next-line anti-slop/no-runtime-typeof -- SAFETY: `server` is a hand-editable mcp.json entry; this is where its `url` becomes a string.+ typeof server.url === 'string' &&+ !hasHeaderAuth &&+ (server.auth === 'oauth' ? status === 'needs-auth' || status === 'error' : !server.auth && status === 'needs-auth')+ )+}++export function capabilitySummary(+ m: Translations['settings']['mcp'],+ probe: McpTestResult,+ server?: McpServerEntry,+ cost?: ServerCost+): string {+ const toolCount = server+ ? countEnabledTools(+ server,+ probe.tools.map(tool => tool.name)+ )+ : probe.tools.length++ const parts = [m.capabilitySummary(toolCount, probe.prompts ?? 0, probe.resources ?? 0)]++ if (cost && cost.tokens !== null && cost.tokens > 0) {+ parts.push(m.costTokens(compactNumber(cost.tokens)))+ }++ if (cost && cost.uses !== null) {+ parts.push(m.usage30d(compactNumber(cost.uses)))+ }++ return parts.join(', ')+}++export function statusLine(+ m: Translations['settings']['mcp'],+ status: ServerStatus,+ probe: Probe | undefined,+ server?: McpServerEntry,+ cost?: ServerCost+): string {+ switch (status) {+ case 'ok': {+ const ok = okProbe(probe)++ return ok ? capabilitySummary(m, ok, server, cost) : ''+ }++ case 'probing':+ return m.statusConnecting++ case 'needs-auth':+ return m.statusNeedsAuth++ case 'error':+ return m.statusError++ case 'off':+ return m.statusOff++ default:+ return ''+ }+}++export function serverCost(+ server: McpServerEntry,+ probe: Probe | undefined,+ name: string,+ toolCalls30d: null | Record<string, number>+): ServerCost {+ const ok = okProbe(probe)++ return {+ tokens: ok ? estimateServerTokens(server, ok.tools) : null,+ uses: toolCalls30d ? serverUsageCount(name, toolCalls30d) : null+ }+}diff --git a/apps/desktop/src/app/capabilities/mcp/use-mcp-draft.ts b/apps/desktop/src/app/capabilities/mcp/use-mcp-draft.tsnew file mode 100644index 00000000000..b9160be0048--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/use-mcp-draft.ts@@ -0,0 +1,195 @@++import { type RefObject, useEffect, useMemo, useRef, useState } from 'react'++import { type CodeEditorApi } from '@/components/chat/code-editor'+import { type McpImportEntry } from '@/lib/mcp-import'+import { getServers, type McpServers } from '@/lib/mcp-servers'+import type { HermesConfigRecord } from '@/types/hermes'++import { parseServersDoc, scanServerBlocks, type ServerBlock, STARTER_ENTRY, uniqueServerKey, wrapDoc } from './mcp-doc'++export interface McpDraft {+ activeBlock: null | ServerBlock+ addServer: () => void+ blocks: ServerBlock[]+ cursor: number+ dirty: boolean+ docVersion: number+ draft: string+ editorApi: RefObject<CodeEditorApi | null>+ focusServer: (name: string) => void+ importServers: (entries: McpImportEntry[]) => void+ patchDraft: (mutate: (doc: McpServers) => McpServers) => void+ reset: () => void+ resetDraft: (entries: McpServers) => void+ selected: null | string+ setCursor: (cursor: number) => void+ setDraft: (draft: string) => void+}++export interface UseMcpDraftOptions {+ config: HermesConfigRecord | null | undefined+ names: string[]+ profilePending: boolean+ servers: McpServers+ writable: boolean+}++export function useMcpDraft({ config, names, profilePending, servers, writable }: UseMcpDraftOptions): McpDraft {+ const [draft, setDraftText] = useState('')+ const [dirty, setDirty] = useState(false)+ const [docVersion, setDocVersion] = useState(0)++ const editorApi = useRef<CodeEditorApi | null>(null)+ const [cursor, setCursor] = useState(0)+ const blocks = useMemo(() => scanServerBlocks(draft), [draft])++ const activeBlock = useMemo(+ () => blocks.find(block => cursor >= block.from && cursor <= block.to) ?? null,+ [blocks, cursor]+ )++ const selected = activeBlock?.name ?? null++ const focusServer = (name: string) => {+ const block = blocks.find(b => b.name === name)++ if (block) {+ editorApi.current?.setCursor(block.from + 1)+ setCursor(block.from + 1)+ }+ }++ const resetDraft = (entries: McpServers) => {+ setDraftText(wrapDoc(entries))+ setDirty(false)+ setDocVersion(version => version + 1)+ }++ const patchDraft = (mutate: (doc: McpServers) => McpServers) => {+ try {+ setDraftText(wrapDoc(mutate(parseServersDoc(draft))))+ setDocVersion(version => version + 1)+ // eslint-disable-next-line no-empty+ } catch {+ }+ }++ const draftSeeded = useRef(false)++ // eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)+ useEffect(() => {+ if (!config || profilePending) {+ return+ }++ if (!draftSeeded.current) {+ draftSeeded.current = true+ resetDraft(getServers(config))++ return+ }++ if (dirty || names.length === 0) {+ return+ }++ try {+ if (Object.keys(parseServersDoc(draft)).length === 0) {+ resetDraft(servers)+ }+ // eslint-disable-next-line no-empty+ } catch {+ }+ }, [config, dirty, draft, names, profilePending, servers])++ const focusKeyIn = (nextDraft: string, key: string) => {+ const from = nextDraft.indexOf(`"${key}"`)++ if (from >= 0) {+ requestAnimationFrame(() => {+ editorApi.current?.setCursor(from + 1)+ setCursor(from + 1)+ })+ }+ }++ const draftBase = (): McpServers => {+ try {+ return parseServersDoc(draft)+ } catch {+ return { ...servers }+ }+ }++ const addServer = () => {+ if (!writable) {+ return+ }++ const base = draftBase()+ const key = uniqueServerKey(base, 'my-server')+ const nextDraft = wrapDoc({ ...base, [key]: STARTER_ENTRY })++ setDraftText(nextDraft)+ setDirty(true)+ setDocVersion(version => version + 1)+ focusKeyIn(nextDraft, key)+ }++ const importServers = (entries: McpImportEntry[]) => {+ if (!writable || entries.length === 0) {+ return+ }++ let base = draftBase()+ let firstKey: null | string = null++ for (const entry of entries) {+ const key = uniqueServerKey(base, entry.name)+ base = { ...base, [key]: entry.config }+ firstKey ??= key+ }++ const nextDraft = wrapDoc(base)+ setDraftText(nextDraft)+ setDirty(true)+ setDocVersion(version => version + 1)++ if (firstKey) {+ focusKeyIn(nextDraft, firstKey)+ }+ }++ const reset = () => {+ draftSeeded.current = false+ setCursor(0)+ setDirty(false)+ setDraftText('')+ setDocVersion(version => version + 1)+ }++ const setDraft = (next: string) => {+ setDraftText(next)+ setDirty(true)+ }++ return {+ activeBlock,+ addServer,+ blocks,+ cursor,+ dirty,+ docVersion,+ draft,+ editorApi,+ focusServer,+ importServers,+ patchDraft,+ reset,+ resetDraft,+ selected,+ setCursor,+ setDraft+ }+}diff --git a/apps/desktop/src/app/capabilities/mcp/use-mcp-probes.ts b/apps/desktop/src/app/capabilities/mcp/use-mcp-probes.tsnew file mode 100644index 00000000000..e31e24105a1--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/use-mcp-probes.ts@@ -0,0 +1,162 @@++import { type RefObject, useEffect, useMemo, useRef, useState } from 'react'++import { type ProfileScope, testMcpServer } from '@/hermes'+import { PROBE_TTL_MS, probeCache, probeKey, serverFingerprint } from '@/lib/mcp-probe-cache'+import type { McpServerEntry, McpServers } from '@/lib/mcp-servers'+import { countEnabledTools } from '@/lib/mcp-tool-filter'++import { serverEnabled } from './mcp-doc'+import { loadMcpUsage, okProbe, type Probe, serverCost, type ServerCost } from './mcp-status'++export interface McpProbes {+ costFor: (name: string, entry: McpServerEntry) => ServerCost+ probes: Record<string, Probe>+ resetForProfileSwitch: () => void+ retainProbes: (entries: McpServers, prevServers: McpServers) => void+ runProbe: (name: string) => Promise<void>+ setProbe: (name: string, value: Probe) => void+ toolCounts: Record<string, { on: number; total: number }>+ usageByServer: Record<string, number>+}++export interface UseMcpProbesOptions {+ appProfile: ProfileScope+ profile?: ProfileScope+ profileEpoch: RefObject<number>+ scopeProfileKey: string+ servers: McpServers+}++export function useMcpProbes({+ appProfile,+ profile,+ profileEpoch,+ scopeProfileKey,+ servers+}: UseMcpProbesOptions): McpProbes {+ const [probes, setProbes] = useState<Record<string, Probe>>({})+ const probesRef = useRef(probes)+ probesRef.current = probes++ const [toolCalls30d, setToolCalls30d] = useState<null | Record<string, number>>(null)++ const setProbe = (serverName: string, value: Probe) => {+ setProbes(current => ({ ...current, [serverName]: value }))+ }++ const runProbe = async (serverName: string) => {+ const epoch = profileEpoch.current+ const key = probeKey(serverName, servers[serverName], scopeProfileKey)+ setProbes(current => ({ ...current, [serverName]: 'probing' }))++ try {+ const result = await testMcpServer(serverName, profile ?? undefined)++ if (profileEpoch.current !== epoch) {+ return+ }++ probeCache.set(key, { at: Date.now(), result })+ setProbes(current => ({ ...current, [serverName]: result }))+ } catch (err) {+ if (profileEpoch.current !== epoch) {+ return+ }++ const result = { ok: false, error: err instanceof Error ? err.message : String(err), tools: [] }+ probeCache.set(key, { at: Date.now(), result })+ setProbes(current => ({ ...current, [serverName]: result }))+ }+ }++ useEffect(() => {+ for (const [serverName, server] of Object.entries(servers)) {+ if (!serverEnabled(server) || probesRef.current[serverName] !== undefined) {+ continue+ }++ const cached = probeCache.get(probeKey(serverName, server, scopeProfileKey))++ if (cached && Date.now() - cached.at < PROBE_TTL_MS) {+ setProbes(current => ({ ...current, [serverName]: cached.result }))+ } else {+ void runProbe(serverName)+ }+ }+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [servers])++ useEffect(() => {+ const epoch = profileEpoch.current++ void loadMcpUsage(scopeProfileKey, profile ?? appProfile ?? null).then(value => {+ if (profileEpoch.current === epoch) {+ setToolCalls30d(value)+ }+ })+ }, [scopeProfileKey, profile, appProfile, profileEpoch])++ const costFor = (serverName: string, server: McpServerEntry): ServerCost =>+ serverCost(server, probes[serverName], serverName, toolCalls30d)++ const toolCounts = useMemo(() => {+ const counts: Record<string, { on: number; total: number }> = {}++ for (const [serverName, server] of Object.entries(servers)) {+ const probe = okProbe(probes[serverName])++ if (probe) {+ counts[serverName] = {+ on: countEnabledTools(+ server,+ probe.tools.map(tool => tool.name)+ ),+ total: probe.tools.length+ }+ }+ }++ return counts+ }, [probes, servers])++ const usageByServer = useMemo(() => {+ const uses: Record<string, number> = {}++ if (!toolCalls30d) {+ return uses+ }++ for (const serverName of Object.keys(servers)) {+ uses[serverName] = serverCost(servers[serverName], probes[serverName], serverName, toolCalls30d).uses ?? 0+ }++ return uses+ }, [probes, servers, toolCalls30d])++ const retainProbes = (entries: McpServers, prevServers: McpServers) => {+ setProbes(current =>+ Object.fromEntries(+ Object.entries(current).filter(+ ([name]) => name in entries && serverFingerprint(entries[name]) === serverFingerprint(prevServers[name] ?? {})+ )+ )+ )+ }++ const resetForProfileSwitch = () => {+ setProbes({})+ setToolCalls30d(null)+ }++ return {+ costFor,+ probes,+ resetForProfileSwitch,+ retainProbes,+ runProbe,+ setProbe,+ toolCounts,+ usageByServer+ }+}diff --git a/apps/desktop/src/app/capabilities/mcp/use-mcp-servers.ts b/apps/desktop/src/app/capabilities/mcp/use-mcp-servers.tsnew file mode 100644index 00000000000..1f1c4fa67ea--- /dev/null+++ b/apps/desktop/src/app/capabilities/mcp/use-mcp-servers.ts@@ -0,0 +1,429 @@++import { useStore } from '@nanostores/react'+import { useQuery } from '@tanstack/react-query'+import { useEffect, useMemo, useRef, useState } from 'react'++import {+ getMcpCatalog,+ type HermesGateway,+ type McpCatalogEntry,+ type McpCatalogResponse,+ type McpTestResult,+ type ProfileScope,+ profileScopeKey,+ saveMcpServers+} from '@/hermes'+import { useI18n } from '@/i18n'+import { completeMcpDesktopOAuth } from '@/lib/mcp-dashboard-oauth'+import { probeCache, probeKey } from '@/lib/mcp-probe-cache'+import { getServers, type McpServerEntry, type McpServers } from '@/lib/mcp-servers'+import { setDisabledTools, toggleToolInServer } from '@/lib/mcp-tool-filter'+import { notify, notifyError } from '@/store/notifications'+import { $activeGatewayProfile, normalizeProfileKey } from '@/store/profile'+import { $activeSessionId } from '@/store/session'+import type { HermesConfigRecord } from '@/types/hermes'++import { hermesConfigCacheWriter, useHermesConfigRecord } from '../../hooks/use-config-record'+import { useOnProfileSwitch } from '../../hooks/use-on-profile-switch'+import { useProfileSwitchLatch } from '../../hooks/use-profile-switch-latch'+import { seedOptions } from '../connectors/data/persist'++import { parseServersDoc, withEnabled } from './mcp-doc'+import { MCP_CATALOG_KEY, type ServerStatus, statusOf } from './mcp-status'+import { type McpDraft, useMcpDraft } from './use-mcp-draft'+import { type McpProbes, useMcpProbes } from './use-mcp-probes'++type PublishedProbes = Pick<McpProbes, 'costFor' | 'probes' | 'runProbe' | 'toolCounts' | 'usageByServer'>++export interface McpServersController extends McpDraft, PublishedProbes {+ addServerEntry: (name: string, entry: McpServerEntry) => Promise<boolean>+ authing: null | string+ authenticate: (name: string) => Promise<void>+ availableCatalog: McpCatalogEntry[]+ catalog: McpCatalogEntry[]+ catalogLoading: boolean+ config: HermesConfigRecord | null+ configError: unknown+ configFailed: boolean+ configLoading: boolean+ descriptionFor: (name: string, entry: McpServerEntry) => null | string+ names: string[]+ onCatalogInstalled: () => Promise<void>+ profilePending: boolean+ refetchConfig: () => void+ removeServer: (name: string) => Promise<boolean>+ saveDoc: () => Promise<void>+ saving: boolean+ servers: McpServers+ setServerEnabled: (name: string, enabled: boolean) => Promise<void>+ setServerTools: (name: string, disabled: string[], discovered: string[]) => Promise<boolean>+ statuses: Record<string, ServerStatus>+ toggleTool: (name: string, toolName: string) => Promise<void>+}++export interface UseMcpServersOptions {+ gateway: HermesGateway | null+ profile?: ProfileScope+}++export function useMcpServers({ gateway, profile }: UseMcpServersOptions): McpServersController {+ const { t } = useI18n()+ const m = t.settings.mcp+ const activeSessionId = useStore($activeSessionId)++ const appProfile = useStore($activeGatewayProfile)+ const scopeProfileKey = profile != null ? profileScopeKey(profile) : normalizeProfileKey(appProfile)++ const {+ data: config,+ isLoading: configLoading,+ isError: configFailed,+ error: configError,+ refetch: refetchConfigQuery,+ dataUpdatedAt: configUpdatedAt,+ errorUpdatedAt: configErroredAt+ } = useHermesConfigRecord(profile)++ const setConfig = hermesConfigCacheWriter(profile)++ const { arm: armProfileLatch, pending: profilePending } = useProfileSwitchLatch({+ dataUpdatedAt: configUpdatedAt,+ errorUpdatedAt: configErroredAt+ })++ const [saving, setSaving] = useState(false)++ const [authing, setAuthing] = useState<null | string>(null)++ const servers = useMemo(() => getServers(config ?? null), [config])+ const names = useMemo(() => Object.keys(servers), [servers])++ const draft = useMcpDraft({ config, names, profilePending, servers, writable: !profilePending })++ const catalogQuery = useQuery({+ ...seedOptions<McpCatalogResponse>(scopeProfileKey, 'bundled'),+ queryKey: [...MCP_CATALOG_KEY, scopeProfileKey],+ queryFn: () => getMcpCatalog(profile ?? undefined),+ staleTime: 5 * 60_000+ })++ const catalog = useMemo(() => catalogQuery.data?.entries ?? [], [catalogQuery.data])++ const availableCatalog = useMemo(+ () => catalog.filter((entry: McpCatalogEntry) => !entry.installed && !(entry.name in servers)),+ [catalog, servers]+ )++ const descriptionFor = (serverName: string, server: McpServerEntry): null | string => {+ const lower = serverName.toLowerCase()++ const match = catalog.find(+ entry =>+ entry.name.toLowerCase() === lower ||+ (entry.url && entry.url === server.url) ||+ (entry.command && entry.command === server.command)+ )++ return match?.description ?? null+ }++ const profileEpoch = useRef(0)++ useEffect(+ () => () => {+ profileEpoch.current += 1+ },+ [scopeProfileKey]+ )++ const fleet = useMcpProbes({ appProfile, profile, profileEpoch, scopeProfileKey, servers })++ useOnProfileSwitch(() => {+ profileEpoch.current += 1+ fleet.resetForProfileSwitch()+ setAuthing(null)+ draft.reset()+ armProfileLatch()+ })++ const silentReload = async () => {+ if (!gateway) {+ return+ }++ try {+ await gateway.request('reload.mcp', { confirm: true, session_id: activeSessionId ?? undefined })+ } catch (err) {+ notifyError(err, m.reloadFailed)+ }+ }++ const authenticate = async (serverName: string) => {+ const epoch = profileEpoch.current+ setAuthing(serverName)+ fleet.setProbe(serverName, 'probing')++ try {+ const flow = await completeMcpDesktopOAuth({+ serverName,+ profile,+ cancelled: () => profileEpoch.current !== epoch+ })++ const result: McpTestResult = { ok: true, tools: flow.tools ?? [] }++ if (profileEpoch.current !== epoch) {+ return+ }++ fleet.setProbe(serverName, result)+ const probedConfig = result.ok ? { ...servers[serverName], auth: 'oauth' } : servers[serverName]+ probeCache.set(probeKey(serverName, probedConfig, scopeProfileKey), { at: Date.now(), result })++ if (result.ok) {+ const nextServers = { ...servers, [serverName]: { ...servers[serverName], auth: 'oauth' } }+ setConfig(current => (current ? { ...current, mcp_servers: nextServers } : current))++ if (draft.dirty) {+ draft.patchDraft(doc =>+ doc[serverName] ? { ...doc, [serverName]: { ...doc[serverName], auth: 'oauth' } } : doc+ )+ } else {+ draft.resetDraft(nextServers)+ }++ notify({+ kind: 'success',+ title: m.authenticatedTitle,+ message: m.authenticatedMessage(serverName, result.tools.length)+ })+ void silentReload()+ } else if (result.error) {+ notifyError(new Error(result.error), serverName)+ }+ } catch (err) {+ if (profileEpoch.current !== epoch) {+ return+ }++ fleet.setProbe(serverName, { ok: false, error: err instanceof Error ? err.message : String(err), tools: [] })+ notifyError(err, serverName)+ } finally {+ if (profileEpoch.current === epoch) {+ setAuthing(null)+ }+ }+ }++ const statuses = useMemo(() => {+ const table: Record<string, ServerStatus> = {}++ for (const [serverName, server] of Object.entries(servers)) {+ table[serverName] = statusOf(server, fleet.probes[serverName])+ }++ return table+ }, [fleet.probes, servers])++ const persist = async (nextServers: McpServers): Promise<boolean> => {+ const epoch = profileEpoch.current+ await saveMcpServers(nextServers, profile ?? undefined)++ if (profileEpoch.current !== epoch) {+ return false+ }++ setConfig(current => ({ ...current, mcp_servers: nextServers }))+ void silentReload()++ return true+ }++ const mirror = (nextServers: McpServers, patch: (doc: McpServers) => McpServers) => {+ if (draft.dirty) {+ draft.patchDraft(patch)+ } else {+ draft.resetDraft(nextServers)+ }+ }++ const onCatalogInstalled = async () => {+ void catalogQuery.refetch()+ const { data } = await refetchConfigQuery()+ const nextServers = getServers(data ?? null)++ mirror(nextServers, doc => ({ ...nextServers, ...doc }))++ void silentReload()+ }++ const writeEntry = async (+ serverName: string,+ transform: (entry: McpServerEntry) => McpServerEntry+ ): Promise<boolean> => {+ const base = servers[serverName]++ if (!base || profilePending) {+ return false+ }++ const next = transform(base)++ try {+ if (!(await persist({ ...servers, [serverName]: next }))) {+ return false+ }++ mirror({ ...servers, [serverName]: next }, doc =>+ doc[serverName] ? { ...doc, [serverName]: transform(doc[serverName]) } : doc+ )++ return true+ } catch (err) {+ notifyError(err, m.saveFailed)++ return false+ }+ }++ const addServerEntry = async (serverName: string, entry: McpServerEntry): Promise<boolean> => {+ if (profilePending || serverName in servers) {+ return false+ }++ const next = { ...servers, [serverName]: entry }++ setSaving(true)++ try {+ if (!(await persist(next))) {+ return false+ }++ mirror(next, doc => ({ ...doc, [serverName]: entry }))+ void fleet.runProbe(serverName)++ return true+ } catch (err) {+ notifyError(err, m.saveFailed)++ return false+ } finally {+ setSaving(false)+ }+ }++ const setServerEnabled = async (serverName: string, enabled: boolean) => {+ if ((await writeEntry(serverName, entry => withEnabled(entry, enabled))) && enabled) {+ void fleet.runProbe(serverName)+ }+ }++ const toggleTool = async (serverName: string, toolName: string) => {+ await writeEntry(serverName, entry => toggleToolInServer(entry, toolName))+ }++ const setServerTools = (serverName: string, disabled: string[], discovered: string[]): Promise<boolean> =>+ writeEntry(serverName, entry => setDisabledTools(entry, disabled, discovered))++ const removeServer = async (serverName: string): Promise<boolean> => {+ if (profilePending) {+ return false+ }++ setSaving(true)++ try {+ const next = { ...servers }+ delete next[serverName]++ if (!(await persist(next))) {+ return false+ }++ mirror(next, doc => {+ const patched = { ...doc }+ delete patched[serverName]++ return patched+ })++ draft.setCursor(0)+ void catalogQuery.refetch()++ return true+ } catch (err) {+ notifyError(err, m.removeFailed)++ return false+ } finally {+ setSaving(false)+ }+ }++ const saveDoc = async () => {+ if (profilePending) {+ return+ }++ let entries: McpServers++ try {+ entries = parseServersDoc(draft.draft)+ } catch (err) {+ notifyError(err, m.invalidJson)++ return+ }++ setSaving(true)++ const prevServers = servers++ try {+ if (!(await persist(entries))) {+ return+ }++ draft.resetDraft(entries)+ fleet.retainProbes(entries, prevServers)+ notify({ kind: 'success', title: m.savedTitle, message: m.savedMessage('mcp.json') })+ } catch (err) {+ notifyError(err, m.saveFailed)+ } finally {+ setSaving(false)+ }+ }++ return {+ ...draft,+ addServerEntry,+ authenticate,+ authing,+ availableCatalog,+ catalog,+ catalogLoading: catalogQuery.isLoading,+ config: config ?? null,+ configError,+ configFailed,+ configLoading,+ costFor: fleet.costFor,+ descriptionFor,+ names,+ onCatalogInstalled,+ probes: fleet.probes,+ profilePending,+ refetchConfig: () => void refetchConfigQuery(),+ removeServer,+ runProbe: fleet.runProbe,+ saveDoc,+ saving,+ servers,+ setServerEnabled,+ setServerTools,+ statuses,+ toggleTool,+ toolCounts: fleet.toolCounts,+ usageByServer: fleet.usageByServer+ }+}diff --git a/apps/desktop/src/app/command-palette/index.tsx b/apps/desktop/src/app/command-palette/index.tsxindex 14ea5991731..98a3cf7f39e 100644--- a/apps/desktop/src/app/command-palette/index.tsx+++ b/apps/desktop/src/app/command-palette/index.tsx@@ -1098,10 +1098,10 @@ function CommandPaletteBody({ onExited }: { onExited: () => void }) {},{icon: Layers3,- id: 'cap-mcp',- keywords: ['mcp', 'servers', 'tools', 'capabilities', 'model context protocol'],- label: `${capLabel}: ${t.skills.tabMcp}`,- run: go(`${CAPABILITIES_ROUTE}?tab=mcp`)+ id: 'cap-connectors',+ keywords: ['connectors', 'apps', 'mcp', 'servers', 'tools', 'capabilities', 'model context protocol'],+ label: `${capLabel}: ${t.connectorsPage.title}`,+ run: go(`${CAPABILITIES_ROUTE}?tab=connectors`)},{icon: Package,@@ -1219,7 +1219,7 @@ function CommandPaletteBody({ onExited }: { onExited: () => void }) {id: `mcp-${name}`,keywords: ['mcp', 'server', 'tool'],label: name,- run: go(`${CAPABILITIES_ROUTE}?tab=mcp&server=${encodeURIComponent(name)}`)+ run: go(`${CAPABILITIES_ROUTE}?tab=connectors&server=${encodeURIComponent(name)}`)}))})}diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.tsindex 8aabbd1f1fa..4da893ab0ed 100644--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts@@ -1,6 +1,7 @@import { useStore } from '@nanostores/react'import { useEffect, useRef } from 'react'+import { resumeAccountConnect } from '@/app/capabilities/connectors/data/deep-link'import { closeActiveTab } from '@/app/chat/close-tab'import { commandFocusedPreview } from '@/app/chat/right-rail/preview-nav'import { openSession } from '@/app/open-session'@@ -331,10 +332,16 @@ export function useDesktopIntegrations({// The user finished a sign-in in their browser and the portal sent them back. Show the card// and wake its watcher; the link's status is not allowed to move any row.if (action.type === 'connection-done') {- void openConnectionDoneLink(action.op, navigate, runtimeId => {- const viaLocalMap = storedSessionIdForNotification(runtimeId, runtimeIdByStoredSessionId.current)+ void resumeAccountConnect(action.op, navigate).then(handled => {+ if (handled) {+ return+ }- return viaLocalMap !== runtimeId ? viaLocalMap : (storedSessionIdForRuntimeId(runtimeId) ?? runtimeId)+ return openConnectionDoneLink(action.op, navigate, runtimeId => {+ const viaLocalMap = storedSessionIdForNotification(runtimeId, runtimeIdByStoredSessionId.current)++ return viaLocalMap !== runtimeId ? viaLocalMap : (storedSessionIdForRuntimeId(runtimeId) ?? runtimeId)+ })})returndiff --git a/apps/desktop/src/app/contrib/mcp-install-deeplink-dialog.tsx b/apps/desktop/src/app/contrib/mcp-install-deeplink-dialog.tsxindex 2de39f013ca..218444fe01e 100644--- a/apps/desktop/src/app/contrib/mcp-install-deeplink-dialog.tsx+++ b/apps/desktop/src/app/contrib/mcp-install-deeplink-dialog.tsx@@ -117,7 +117,7 @@ export function McpInstallDeepLinkDialog() {setHermesConfigCache(previous => (previous ? { ...previous, mcp_servers: nextServers } : previous))notify({ kind: 'success', title: m.savedTitle, message: m.savedMessage(trimmedName) })$mcpInstallRequest.set(null)- navigate(`/capabilities?tab=mcp&server=${encodeURIComponent(trimmedName)}`)+ navigate(`/capabilities?tab=connectors&server=${encodeURIComponent(trimmedName)}`)} catch (err) {setError(readableError(err, m.saveFailed).message)} finally {diff --git a/apps/desktop/src/app/routes.ts b/apps/desktop/src/app/routes.tsindex e9a9b4a9eab..0013ed8689c 100644--- a/apps/desktop/src/app/routes.ts+++ b/apps/desktop/src/app/routes.ts@@ -164,9 +164,9 @@ export function hidesFixedTitlebarClusters(view: AppView): boolean {}/** The pathname of a router target. Every classifier below reasons about a- * PATH, but callers navigate to full targets (`/capabilities?tab=mcp`), and an- * unstripped query reaches the session-id parser — `/capabilities?tab=mcp` reads as- * the session `skills?tab=mcp`, so Capabilities classifies as a chat.+ * PATH, but callers navigate to full targets (`/capabilities?tab=connectors`), and an+ * unstripped query reaches the session-id parser — `/capabilities?tab=connectors` reads+ * as the session `skills?tab=connectors`, so Capabilities classifies as a chat.* `sessionRoute` percent-encodes ids, so `?`/`#` can only start a query or a* hash. */export function routePathname(to: string): string {diff --git a/apps/desktop/src/app/routes.workspace-reveal.test.ts b/apps/desktop/src/app/routes.workspace-reveal.test.tsindex 925036cb106..dd74f6655be 100644--- a/apps/desktop/src/app/routes.workspace-reveal.test.ts+++ b/apps/desktop/src/app/routes.workspace-reveal.test.ts@@ -69,8 +69,8 @@ afterEach(() => {describe('routePathname', () => {it('keeps a bare path and drops a query or hash', () => {expect(routePathname(CAPABILITIES_ROUTE)).toBe('/capabilities')- expect(routePathname('/capabilities?tab=mcp')).toBe('/capabilities')- expect(routePathname('/capabilities?tab=mcp&server=ctx7')).toBe('/capabilities')+ expect(routePathname('/capabilities?tab=connectors')).toBe('/capabilities')+ expect(routePathname('/capabilities?tab=connectors&server=ctx7')).toBe('/capabilities')expect(routePathname('/settings#keys')).toBe('/settings')})@@ -89,7 +89,7 @@ describe('classification of targets carrying a query', () => {it.each([[`${CAPABILITIES_ROUTE}?tab=skills`, 'capabilities'],[`${CAPABILITIES_ROUTE}?tab=toolsets`, 'capabilities'],- [`${CAPABILITIES_ROUTE}?tab=mcp&server=ctx7`, 'capabilities'],+ [`${CAPABILITIES_ROUTE}?tab=connectors&server=ctx7`, 'capabilities'],[`${SETTINGS_ROUTE}?tab=keys`, 'settings']])('%s is not a session route', (to, view) => {expect(routeSessionId(to)).toBeNull()@@ -106,7 +106,7 @@ describe('syncWorkspaceRoute', () => {})it('fronts on a page route reached with a query', () => {- syncWorkspaceRoute(`${CAPABILITIES_ROUTE}?tab=mcp`)+ syncWorkspaceRoute(`${CAPABILITIES_ROUTE}?tab=connectors`)expect($workspaceIsPage.get()).toBe(true)expect(fronted()).toBe(true)@@ -164,7 +164,7 @@ describe('navigateToWorkspacePage', () => {it.each([`${CAPABILITIES_ROUTE}?tab=skills`,`${CAPABILITIES_ROUTE}?tab=toolsets`,- `${CAPABILITIES_ROUTE}?tab=mcp&server=ctx7`+ `${CAPABILITIES_ROUTE}?tab=connectors&server=ctx7`])('fronts for the palette target %s', to => {navigateToWorkspacePage(vi.fn(), to)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.tsindex 4b60698e73c..b367a9cf499 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.ts@@ -1,5 +1,6 @@import type { ConnectionRequestPayload, ConnectionUpdatePayload, GatewayEvent } from '@hermes/shared'+import { applyAccountConnectionUpdate } from '@/app/capabilities/connectors/data/account-operations'import { pendingClarifyToolPayload } from '@/app/session/hooks/use-session-actions/restore-pending-clarify'import { connectionRequestToolPayload } from '@/app/session/hooks/use-session-actions/restore-pending-connection'import { translateNow } from '@/i18n'@@ -72,6 +73,12 @@ export function handleInputRequestEvent(ctx: GatewayEventContext): boolean {}if (isConnectionUpdateEvent(event)) {+ if (event.payload.owner.type === 'account') {+ applyAccountConnectionUpdate(event.payload)++ return true+ }+updateConnectionRequest(sessionId ?? null, event.payload)if (event.payload.settled && sessionId) {diff --git a/apps/desktop/src/app/settings/moved-tabs.test.ts b/apps/desktop/src/app/settings/moved-tabs.test.tsindex 0c7c6911c7c..3a0aa7a0624 100644--- a/apps/desktop/src/app/settings/moved-tabs.test.ts+++ b/apps/desktop/src/app/settings/moved-tabs.test.ts@@ -8,7 +8,7 @@ describe('movedSettingsTabRedirect', () => {expect(movedSettingsTabRedirect('?tab=plugins&plugin=demo%2Fplugin')).toBe('/capabilities?tab=plugins&plugin=demo%2Fplugin')- expect(movedSettingsTabRedirect('?tab=mcp&server=github')).toBe('/capabilities?tab=mcp&server=github')+ expect(movedSettingsTabRedirect('?tab=mcp&server=github')).toBe('/capabilities?tab=connectors&server=github')})it('leaves live Settings tabs alone', () => {diff --git a/apps/desktop/src/app/settings/moved-tabs.ts b/apps/desktop/src/app/settings/moved-tabs.tsindex a0a3f9d3dfa..551f9f48e48 100644--- a/apps/desktop/src/app/settings/moved-tabs.ts+++ b/apps/desktop/src/app/settings/moved-tabs.ts@@ -1,23 +1,20 @@import { CAPABILITIES_ROUTE } from '../routes'-// Settings tabs that now live in Capabilities → the row-selector param each-// carries (`?server=` for MCP, `?plugin=` for Plugins). Old bookmarks and-// palette links keep resolving to the same row on the new page.-const MOVED_TO_CAPABILITIES: Record<string, string> = { mcp: 'server', plugins: 'plugin' }+const MOVED_TO_CAPABILITIES: Record<string, { param: string; tab: string }> = {+ mcp: { param: 'server', tab: 'connectors' },+ plugins: { param: 'plugin', tab: 'plugins' }+}-/** The Capabilities URL an old `/settings?tab=<moved>` query should land on,- * or null when the tab still belongs to Settings. */export function movedSettingsTabRedirect(search: string): null | string {const params = new URLSearchParams(search)- const tab = params.get('tab')- const rowParam = tab ? MOVED_TO_CAPABILITIES[tab] : undefined+ const moved = MOVED_TO_CAPABILITIES[params.get('tab') ?? '']- if (!tab || rowParam === undefined) {+ if (moved === undefined) {return null}- const row = params.get(rowParam)- const suffix = row ? `&${rowParam}=${encodeURIComponent(row)}` : ''+ const row = params.get(moved.param)+ const suffix = row ? `&${moved.param}=${encodeURIComponent(row)}` : ''- return `${CAPABILITIES_ROUTE}?tab=${tab}${suffix}`+ return `${CAPABILITIES_ROUTE}?tab=${moved.tab}${suffix}`}diff --git a/apps/desktop/src/components/ui/connector-card.tsx b/apps/desktop/src/components/ui/connector-card.tsxindex be55ca6e4ef..0ffe0fe8918 100644--- a/apps/desktop/src/components/ui/connector-card.tsx+++ b/apps/desktop/src/components/ui/connector-card.tsx@@ -72,7 +72,7 @@ export function ConnectorRow({ action, connector, cue, mark, markLabel }: Connec</span><span className="flex w-22 shrink-0 justify-end">{action ? (- <span className="inline-flex h-6 w-full items-stretch overflow-hidden rounded-md border border-primary/25 bg-primary/10 text-primary">+ <span className="inline-flex h-6 w-22 items-stretch overflow-hidden rounded-md border border-primary/25 bg-primary/10 text-primary"><ButtonclassName="h-full w-full rounded-none px-2 text-xs font-medium text-primary hover:bg-primary/15 hover:text-primary"disabled={action.disabled}diff --git a/apps/desktop/src/components/ui/switch.tsx b/apps/desktop/src/components/ui/switch.tsxindex 2b6b72cadea..45d006435bc 100644--- a/apps/desktop/src/components/ui/switch.tsx+++ b/apps/desktop/src/components/ui/switch.tsx@@ -5,7 +5,7 @@ import * as React from 'react'import { cn } from '@/lib/utils'const switchVariants = cva(- 'peer inline-flex shrink-0 items-center rounded-full border border-[color-mix(in_srgb,var(--dt-foreground)_18%,transparent)] bg-[color-mix(in_srgb,var(--dt-background)_58%,var(--dt-input))] shadow-[inset_0_0_0_0.0625rem_color-mix(in_srgb,var(--dt-foreground)_8%,transparent)] transition-colors outline-none focus-visible:border-ring focus-visible:ring-[0.1875rem] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-transparent data-[state=checked]:bg-primary',+ 'peer inline-flex shrink-0 items-center rounded-full border border-[color-mix(in_srgb,var(--dt-foreground)_18%,transparent)] bg-[color-mix(in_srgb,var(--dt-background)_58%,var(--dt-input))] shadow-[inset_0_0_0_0.0625rem_color-mix(in_srgb,var(--dt-foreground)_8%,transparent)] transition-colors outline-none focus-visible:border-ring focus-visible:ring-[0.1875rem] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:border-transparent data-[state=checked]:bg-primary disabled:data-[state=checked]:bg-(--ui-text-tertiary)',{variants: {size: {diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 0861d6ac13a..ce4389f027c 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -36,6 +36,246 @@ export const en: Translations = {required: 'Required'},+ // `connectors.*` above stays the onboarding and chat vocabulary; these are the page's own, and the two are not shared.+ connectorsPage: {+ title: 'Connectors',+ searchPlaceholder: (count: number) => `Search ${count} apps`,+ filterCategory: 'Category',+ categoryAll: 'All categories',+ uncategorised: 'Uncategorised',++ residencyLocal: 'On this device',++ segment: {+ all: 'All',+ available: 'Available',+ connected: 'Connected',+ off: 'Turned off'+ },++ group: {+ connected: 'Connected',+ connectedNote: 'Broken connections first.',+ available: 'Available',+ off: 'Turned off',+ offNote: 'Sign-ins are kept.'+ },++ card: {+ kindManaged: 'Managed',+ kindCatalog: 'MCP · Catalog',+ kindCustom: 'MCP · Custom',+ kindPlugin: (plugin: string) => `MCP · Plugin ${plugin}`,+ inCatalog: 'In the Hermes catalog',+ hostedTwin: 'Managed version available',+ alsoLocal: 'Also runs on this device',+ open: (name: string) => `Open ${name}`,+ turnServerOn: (name: string) => `Turn ${name} on`,+ turnServerOff: (name: string) => `Turn ${name} off`,+ state: {+ accessExpired: 'Access expired',+ available: 'Available',+ connected: 'Connected',+ connecting: 'Connecting',+ connectionUnknown: 'State unknown',+ couldNotConnect: 'Could not connect',+ offByYourOrganisation: 'Off by your organisation',+ offForYou: 'Off for you',+ serverConnecting: 'Connecting…',+ serverError: 'Error',+ serverNeedsAuth: 'Needs authentication',+ serverOff: 'Off',+ serverOn: 'On',+ serverOnUnused: 'On, unused'+ },+ fact: {+ tools: (count: number) => `${count} tool${count === 1 ? '' : 's'}`,+ toolsOff: (count: number) => `${count} tool${count === 1 ? '' : 's'} off`,+ toolsOn: (count: number) => `${count} tool${count === 1 ? '' : 's'} on`,+ toolsSomeOn: (total: number, on: number) => `${total} tools, ${on} on`+ },+ verb: {+ authenticate: 'Authenticate',+ connect: 'Connect',+ install: 'Install',+ openLogs: 'Open logs',+ reconnect: 'Reconnect',+ stopWaiting: 'Stop waiting',+ tryAgain: 'Try again',+ turnBackOn: 'Turn back on'+ },+ reason: {+ finishSignIn: 'Finish the sign-in in your browser.',+ reconnect: 'Reconnect to keep this app working.',+ serverError: 'The server refused the connection.',+ serverNeedsAuth: 'Sign in to let this server answer.'+ }+ },++ page: {+ loading: 'Reading the catalog and the servers on this computer',+ emptyTitle: 'No apps here yet. Add a server on this computer to get started.',+ noMatchTitle: 'No matching apps',+ noMatchBody: 'Nothing here matches. Point Hermes at your own MCP server to add it.',+ clearSearch: 'Clear the search',+ hostedFailedTitle: 'Could not reach the hosted apps.',+ hostedFailedBody: 'The servers on this computer are unaffected and still running. Nothing was turned off.',+ retry: 'Retry',+ matchesElsewhere: (count: number) => `${count} more match${count === 1 ? '' : 'es'} in other groups.`,+ showAllMatches: 'Show all matches',+ segmentNoMatch: (segment: string) => `No match in ${segment}, so every match is shown.`,+ freeTierNote: 'Connections stay on this computer until you sign in.',+ signInLine: 'Sign in to Nous to use managed apps.',+ signIn: 'Sign in',+ managedUnavailable: 'Managed apps are not available for this account yet.',+ writeFailed: 'That change was not saved.',+ refreshFailed: 'The tool list was not refreshed.',+ disconnectNoAccount: 'Hermes has no account to disconnect here. Refresh the page and try again.'+ },++ add: {+ action: 'Add your own',+ title: 'Connect to a custom MCP',+ hint: 'one new entry in mcp.json on this device',+ pasteLabel: 'Paste a command or a snippet',+ pastePlaceholder: 'npx -y @modelcontextprotocol/server-filesystem /path/to/dir',+ pasteNoMatch: 'Nothing here reads as a server. Fill the fields below instead.',+ name: 'Name',+ nameTaken: 'That name is already used.',+ type: 'Type',+ typeStdio: 'STDIO',+ typeHttp: 'Streamable HTTP',+ command: 'Command to launch',+ args: 'Arguments',+ addArg: '+ Add argument',+ envVars: 'Environment variables',+ addEnvVar: '+ Add environment variable',+ passthrough: 'Environment variable passthrough',+ addPassthrough: '+ Add variable',+ cwd: 'Working directory',+ url: 'URL',+ headers: 'Headers',+ addHeader: '+ Add header',+ auth: 'Auth',+ authNone: 'None',+ authOauth: 'OAuth',+ authBearer: 'Bearer token',+ keyPlaceholder: 'KEY',+ valuePlaceholder: 'value',+ removeRow: 'Remove this row',+ editJson: 'Edit mcp.json',+ saveFailed: 'That server was not saved.'+ },++ dialog: {+ disconnect: 'Disconnect',+ disconnectTitle: (name: string) => `Disconnect ${name}?`,+ disconnectBody: 'Hermes stops acting as this account. You can connect again at any time.',+ menuRefreshTools: 'Refresh tools',+ moreActions: 'More actions',+ removeServerTitle: (name: string) => `Remove ${name}?`,+ removeServerBody: 'The entry leaves mcp.json on this computer. Nothing else is deleted.',+ appSwitch: (name: string) => `Hermes can use ${name}`,+ waysTitle: (name: string) => `How Hermes reaches ${name}`,+ wayHosted: 'Managed',+ bothOn: (name: string) => `Both are on, so Hermes sees every ${name} tool twice.`,+ turnOffLocal: 'Turn off the local server',+ providedByPlugin: (plugin: string) => `Provided by plugin ${plugin}`,+ openPlugins: 'Open the Plugins tab',+ // Verbatim, by decision of the design of record.+ nousLine: 'Nous apps follow your account, not the profile.',+ rulesReadOnly: 'Rules cannot be changed right now.',+ rulesAppOff: (name: string) => `Turn ${name} on to change its tools.`,+ rulesSignIn: 'Sign in to change what Hermes may do here.',+ orgNote: (count: number) => `Your organisation turned ${count} tools off.`,+ orgLink: 'Open the connectors admin',+ connectEnded: 'The sign-in did not finish.',+ connectOpenAgain: 'Open the link again',+ tokensPerCall: 'tokens per call',+ usesPerMonth: 'uses in 30 days',+ advanced: 'Advanced',+ advancedHint: 'the mcp.json entry and logs'+ },++ tools: {+ title: 'Tools',+ notInstalledBody: 'Install it on this device to see the tools it brings.',+ summaryTitle: (name: string) => `What Hermes may do with ${name}`,+ summaryPreviewTitle: (name: string) => `What Hermes could do with ${name} once you connect`,+ summaryCount: (count: number) => `${count} tool${count === 1 ? '' : 's'}`,+ summaryAllTools: 'All tools',+ summaryOther: 'Other',+ allToolsSwitch: 'Turn every tool on or off',+ summaryAllOn: 'all on',+ summarySomeOn: (on: number, total: number) => `${on} of ${total} on`,+ summaryOff: 'off',+ showAllTools: (count: number) => `Show all ${count} tool${count === 1 ? '' : 's'}`,+ showSummary: 'Show summary',+ facetSwitch: (facet: string) => `Turn ${facet} tools on or off`,+ moreHints: (count: number) => `+${count}`,+ staleSignIn: 'Sign in to read the latest tool list.',+ searchCountPlaceholder: (count: number) => `Search ${count} tools`,+ toolList: (name: string) => `${name} tools`,+ categorySelect: (count: number) => `${count} categories`,+ showDeprecated: (count: number) => `Show ${count} deprecated`,+ hideDeprecated: (count: number) => `Hide ${count} deprecated`,+ quickReadOnly: 'Read only',+ quickNoDestructive: 'Turn off destructive',+ quickEverythingOn: 'Everything on',+ lockedHint: 'off by your organisation',+ turnToolOn: (tool: string) => `Turn ${tool} on`,+ turnToolOff: (tool: string) => `Turn ${tool} off`,+ showDetails: (tool: string) => `Show what ${tool} does`,+ hideDetails: (tool: string) => `Hide what ${tool} does`,+ noMatch: 'No tool matches these filters.',+ loading: 'Reading the tool list',+ unavailableLine: 'Tool list unavailable.',+ needsAuthTitle: (name: string) => `Sign in to ${name} to read its tools.`,+ needsAuthBody: 'The sign-in stays on this computer. Nothing leaves it.',+ retry: 'Retry',+ goneTitle: (name: string) => `${name} left the catalog.`,+ goneBody: 'Hermes cannot call it any more. The row stays until you remove it, so nothing vanishes.',+ remove: 'Remove',+ offTitle: (name: string) => `${name} is off.`,+ offBody: 'Turn it on with the switch above to read the tools it brings.',+ signedOutTitle: 'Sign in to Nous to read the tool list.',+ signedOutBody: 'Your servers on this computer are unaffected.',+ conflictTitle: 'Someone changed this rule while you were editing.',+ // Two sentences at most, and the second says the work is still here.+ conflictBody: (theyOff: number, theyOn: number) => {+ const they = [+ theyOff > 0 ? `turned off ${theyOff} tool${theyOff === 1 ? '' : 's'} you have on` : '',+ theyOn > 0 ? `left ${theyOn} tool${theyOn === 1 ? '' : 's'} on that you turned off` : ''+ ].filter(Boolean)++ return `${they.length > 0 ? `They ${they.join(', and ')}. ` : ''}Your edits stay on screen; nothing was written.`+ },+ conflictReload: 'Reload their version',+ conflictSave: 'Save over their version',+ saveFailed: 'Those tool rules were not saved.',+ footerDirty: (off: number, backOn: number) =>+ `${off} tool${off === 1 ? '' : 's'} off, ${backOn === 0 ? 'none' : backOn} back on`,+ discard: 'Discard',+ save: 'Save changes',+ saving: 'Saving...'+ },++ // The label rides in every tool row, so it stays short enough not to widen one.+ vocabulary: {+ facetRead: { label: 'Read', long: 'Reads data out of this app. It changes nothing.' },+ facetWrite: { label: 'Write', long: 'Creates or changes something in this app.' },+ facetDestructive: { label: 'Destructive', long: 'Can remove something in this app for good.' },+ facetUnclassified: { label: 'Unknown effect', long: 'The app never said what this tool does.' },+ hintReadOnly: { label: 'Read only', long: 'The tool declares that it only reads.' },+ hintCreate: { label: 'Creates', long: 'Makes something new.' },+ hintUpdate: { label: 'Updates', long: 'Changes something that already exists.' },+ hintDelete: { label: 'Deletes', long: 'Removes something.' },+ hintDestructive: { label: 'Destructive', long: 'The change it makes cannot be undone here.' },+ hintIdempotent: { label: 'Repeatable', long: 'Running it twice does what running it once does.' },+ hintOpenWorld: { label: 'External', long: 'Reaches something outside this app.' }+ }+ },+sessionImport: {title: 'Continue from another app',subtitle: 'Bring a conversation into Hermes and pick up where you left off.',diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 50af98e54e8..87f4a84ef93 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -91,6 +91,225 @@ export interface Translations {authorizedToolsUnavailable: stringrequired: string}+ connectorsPage: {+ title: string+ searchPlaceholder: (count: number) => string+ filterCategory: string+ categoryAll: string+ uncategorised: string+ residencyLocal: string+ segment: {+ all: string+ available: string+ connected: string+ off: string+ }+ group: {+ connected: string+ connectedNote: string+ available: string+ off: string+ offNote: string+ }+ card: {+ kindManaged: string+ kindCatalog: string+ kindCustom: string+ kindPlugin: (plugin: string) => string+ inCatalog: string+ hostedTwin: string+ alsoLocal: string+ open: (name: string) => string+ turnServerOn: (name: string) => string+ turnServerOff: (name: string) => string+ state: {+ accessExpired: string+ available: string+ connected: string+ connecting: string+ connectionUnknown: string+ couldNotConnect: string+ offByYourOrganisation: string+ offForYou: string+ serverConnecting: string+ serverError: string+ serverNeedsAuth: string+ serverOff: string+ serverOn: string+ serverOnUnused: string+ }+ fact: {+ tools: (count: number) => string+ toolsOff: (count: number) => string+ toolsOn: (count: number) => string+ toolsSomeOn: (total: number, on: number) => string+ }+ verb: {+ authenticate: string+ connect: string+ install: string+ openLogs: string+ reconnect: string+ stopWaiting: string+ tryAgain: string+ turnBackOn: string+ }+ reason: {+ finishSignIn: string+ reconnect: string+ serverError: string+ serverNeedsAuth: string+ }+ }+ page: {+ loading: string+ emptyTitle: string+ noMatchTitle: string+ noMatchBody: string+ clearSearch: string+ hostedFailedTitle: string+ hostedFailedBody: string+ retry: string+ matchesElsewhere: (count: number) => string+ showAllMatches: string+ segmentNoMatch: (segment: string) => string+ freeTierNote: string+ signInLine: string+ signIn: string+ managedUnavailable: string+ writeFailed: string+ refreshFailed: string+ disconnectNoAccount: string+ }+ add: {+ action: string+ title: string+ hint: string+ pasteLabel: string+ pastePlaceholder: string+ pasteNoMatch: string+ name: string+ nameTaken: string+ type: string+ typeStdio: string+ typeHttp: string+ command: string+ args: string+ addArg: string+ envVars: string+ addEnvVar: string+ passthrough: string+ addPassthrough: string+ cwd: string+ url: string+ headers: string+ addHeader: string+ auth: string+ authNone: string+ authOauth: string+ authBearer: string+ keyPlaceholder: string+ valuePlaceholder: string+ removeRow: string+ editJson: string+ saveFailed: string+ }+ dialog: {+ disconnect: string+ disconnectTitle: (name: string) => string+ disconnectBody: string+ menuRefreshTools: string+ moreActions: string+ removeServerTitle: (name: string) => string+ removeServerBody: string+ appSwitch: (name: string) => string+ waysTitle: (name: string) => string+ wayHosted: string+ bothOn: (name: string) => string+ turnOffLocal: string+ providedByPlugin: (plugin: string) => string+ openPlugins: string+ nousLine: string+ rulesReadOnly: string+ rulesAppOff: (name: string) => string+ rulesSignIn: string+ orgNote: (count: number) => string+ orgLink: string+ connectEnded: string+ connectOpenAgain: string+ tokensPerCall: string+ usesPerMonth: string+ advanced: string+ advancedHint: string+ }+ tools: {+ title: string+ notInstalledBody: string+ summaryTitle: (name: string) => string+ summaryPreviewTitle: (name: string) => string+ summaryCount: (count: number) => string+ summaryAllTools: string+ summaryOther: string+ allToolsSwitch: string+ summaryAllOn: string+ summarySomeOn: (on: number, total: number) => string+ summaryOff: string+ showAllTools: (count: number) => string+ showSummary: string+ facetSwitch: (facet: string) => string+ moreHints: (count: number) => string+ staleSignIn: string+ searchCountPlaceholder: (count: number) => string+ toolList: (name: string) => string+ categorySelect: (count: number) => string+ showDeprecated: (count: number) => string+ hideDeprecated: (count: number) => string+ quickReadOnly: string+ quickNoDestructive: string+ quickEverythingOn: string+ lockedHint: string+ turnToolOn: (tool: string) => string+ turnToolOff: (tool: string) => string+ showDetails: (tool: string) => string+ hideDetails: (tool: string) => string+ noMatch: string+ loading: string+ unavailableLine: string+ needsAuthTitle: (name: string) => string+ needsAuthBody: string+ retry: string+ goneTitle: (name: string) => string+ goneBody: string+ remove: string+ offTitle: (name: string) => string+ offBody: string+ signedOutTitle: string+ signedOutBody: string+ conflictTitle: string+ conflictBody: (theyOff: number, theyOn: number) => string+ conflictReload: string+ conflictSave: string+ saveFailed: string+ footerDirty: (off: number, backOn: number) => string+ discard: string+ save: string+ saving: string+ }+ vocabulary: Record<+ | 'facetDestructive'+ | 'facetRead'+ | 'facetUnclassified'+ | 'facetWrite'+ | 'hintCreate'+ | 'hintDelete'+ | 'hintDestructive'+ | 'hintIdempotent'+ | 'hintOpenWorld'+ | 'hintReadOnly'+ | 'hintUpdate',+ { label: string; long: string }+ >+ }sessionImport: {title: stringsubtitle: stringdiff --git a/apps/desktop/src/lib/connector-tools.ts b/apps/desktop/src/lib/connector-tools.tsindex d2d992ceef4..b0cd5b99ef2 100644--- a/apps/desktop/src/lib/connector-tools.ts+++ b/apps/desktop/src/lib/connector-tools.ts@@ -87,9 +87,22 @@ const TITLES: ConnectorTitles = {}export function connectorTitle(slug: string): string {- return TITLES[slug] ?? slug.replace(/[_-]+/g, ' ').replace(/\b\w/g, letter => letter.toUpperCase())+ return (+ TITLES[slug] ??+ slug+ .replace(/[_-]+/g, ' ')+ .replace(/\b\w/g, letter => letter.toUpperCase())+ .replace(/\bMcp\b/g, 'MCP')+ )}+/** The identity every connector row and summary renders from. */+export const connectorSubject = (slug: string) => ({+ iconUrl: connectorIconUrl(slug),+ name: slug,+ title: connectorTitle(slug)+})+export function connectorToolName(name: string): { connector: string; action: string } | null {const match = /^connectors__([a-z0-9_-]+)__(.+)$/i.exec(name)diff --git a/apps/desktop/src/lib/mcp-import.ts b/apps/desktop/src/lib/mcp-import.tsindex 7437c375ea6..ed358ec51e5 100644--- a/apps/desktop/src/lib/mcp-import.ts+++ b/apps/desktop/src/lib/mcp-import.ts@@ -280,7 +280,118 @@ function fromClaudeAdd(tokens: string[]): McpImportEntry | null {return { config, name }}-// cursor://anysphere.cursor-deeplink/mcp/install?name=X&config=<base64 JSON>+interface HermesAddFlags {+ args: string[]+ auth: null | string+ command: null | string+ env: Record<string, string>+ name: null | string+ url: null | string+}++const ARGS_END = -1++const emptyHermesFlags = (): HermesAddFlags => ({+ args: [],+ auth: null,+ command: null,+ env: {},+ name: null,+ url: null+})++function readEnvPairs(env: Record<string, string>, tokens: string[], index: number): number {+ let i = index++ while (i + 1 < tokens.length && !tokens[i + 1].startsWith('-')) {+ const pair = tokens[++i]+ const eq = pair.indexOf('=')++ if (eq > 0) {+ env[pair.slice(0, eq)] = pair.slice(eq + 1)+ }+ }++ return i+}++function readHermesToken(flags: HermesAddFlags, tokens: string[], index: number): number {+ const token = tokens[index]++ if (token === '--args') {+ const rest = tokens.slice(index + 1)+ flags.args = rest[0] === '--' ? rest.slice(1) : rest++ return ARGS_END+ }++ if (token === '--url' || token === '--command' || token === '--auth') {+ const value = tokens[index + 1] ?? null++ if (token === '--url') {+ flags.url = value+ } else if (token === '--command') {+ flags.command = value+ } else {+ flags.auth = value+ }++ return index + 1+ }++ if (token === '--env') {+ return readEnvPairs(flags.env, tokens, index)+ }++ if (token === '--connect-timeout' || token === '--preset') {+ return index + 1+ }++ if (!token.startsWith('-') && !flags.name) {+ flags.name = token+ }++ return index+}++function hermesEntry(flags: HermesAddFlags): McpImportEntry | null {+ const { args, auth, command, env, name, url } = flags++ if (!name || (!url && !command)) {+ return null+ }++ const config: McpImportEntry['config'] = url ? { url } : { command }++ if (!url && args.length > 0) {+ config.args = args+ }++ if (auth) {+ config.auth = auth+ }++ if (Object.keys(env).length > 0) {+ config.env = env+ }++ return { config, name }+}++function fromHermesAdd(tokens: string[]): McpImportEntry | null {+ const flags = emptyHermesFlags()++ for (let i = 3; i < tokens.length; i++) {+ i = readHermesToken(flags, tokens, i)++ if (i === ARGS_END) {+ break+ }+ }++ return hermesEntry(flags)+}+function fromCursorDeeplink(text: string): McpImportEntry[] | null {const match = /^cursor:\/\/anysphere\.cursor-deeplink\/mcp\/install\?(.+)$/i.exec(text)@@ -382,6 +493,12 @@ function parseLine(line: string): McpImportEntry[] | null {return entry ? [entry] : null}+ if (tokens[0] === 'hermes' && tokens[1] === 'mcp' && tokens[2] === 'add') {+ const entry = fromHermesAdd(tokens)++ return entry ? [entry] : null+ }+const entry = fromCommandLine(tokens)return entry ? [entry] : nulldiff --git a/apps/desktop/src/lib/mcp-servers.ts b/apps/desktop/src/lib/mcp-servers.tsindex 58db1569ee8..eed292f5cfb 100644--- a/apps/desktop/src/lib/mcp-servers.ts+++ b/apps/desktop/src/lib/mcp-servers.ts@@ -6,6 +6,8 @@export type McpServers = Record<string, Record<string, unknown>>+export type McpServerEntry = McpServers[string]+export const isServerShape = (value: Record<string, unknown>) =>typeof value.command === 'string' || typeof value.url === 'string'diff --git a/apps/desktop/src/lib/mcp-tool-filter.test.ts b/apps/desktop/src/lib/mcp-tool-filter.test.tsindex 4f11840d07a..bcf5f762d7d 100644--- a/apps/desktop/src/lib/mcp-tool-filter.test.ts+++ b/apps/desktop/src/lib/mcp-tool-filter.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest'-import { countEnabledTools, isToolEnabled, readToolsFilter, toggleToolInServer } from './mcp-tool-filter'+import {+ countEnabledTools,+ isToolEnabled,+ readToolsFilter,+ setDisabledTools,+ toggleToolInServer+} from './mcp-tool-filter'describe('readToolsFilter', () => {it('returns empty when no tools object', () => {@@ -79,6 +85,24 @@ describe('toggleToolInServer', () => {})})+describe('setDisabledTools', () => {+ it('keeps a stored rule for a tool the current probe did not return', () => {+ expect(setDisabledTools({ tools: { exclude: ['dangerous_tool'] } }, ['b'], ['a', 'b']).tools).toEqual({+ exclude: ['b', 'dangerous_tool']+ })++ expect(setDisabledTools({ tools: { exclude: ['dangerous_tool'] } }, [], ['a', 'b']).tools).toEqual({+ exclude: ['dangerous_tool']+ })++ expect(setDisabledTools({ tools: { include: ['a', 'rare_tool'] } }, ['b'], ['a', 'b']).tools).toEqual({+ include: ['a', 'rare_tool']+ })++ expect(setDisabledTools({ tools: { exclude: ['b'] } }, [], ['a', 'b']).tools).toBeUndefined()+ })+})+describe('countEnabledTools', () => {it('counts enabled tools out of a discovered list', () => {const server = { tools: { exclude: ['b'] } }diff --git a/apps/desktop/src/lib/mcp-tool-filter.ts b/apps/desktop/src/lib/mcp-tool-filter.tsindex a0fabf46437..8f324392e75 100644--- a/apps/desktop/src/lib/mcp-tool-filter.ts+++ b/apps/desktop/src/lib/mcp-tool-filter.ts@@ -65,5 +65,35 @@ export function toggleToolInServer(server: ServerConfig, name: string): ServerCoreturn next}+export function setDisabledTools(server: ServerConfig, disabled: string[], discovered: string[]) {+ const { exclude, include } = readToolsFilter(server)+ const off = new Set(disabled)+ const seen = new Set(discovered)+ const tools = { ...toolsObject(server) }+ const kept = (stored: string[] | undefined) => (stored ?? []).filter(name => !seen.has(name))++ if (include !== undefined) {+ tools.include = [...discovered.filter(name => !off.has(name)), ...kept(include)]+ } else {+ const names = [...discovered.filter(name => off.has(name)), ...kept(exclude)]++ if (names.length) {+ tools.exclude = names+ } else {+ delete tools.exclude+ }+ }++ const next = { ...server }++ if (Object.keys(tools).length) {+ next.tools = tools+ } else {+ delete next.tools+ }++ return next+}+export const countEnabledTools = (server: ServerConfig | null | undefined, names: string[]): number =>names.filter(name => isToolEnabled(server, name)).lengthdiff --git a/apps/desktop/src/store/connection-request.ts b/apps/desktop/src/store/connection-request.tsindex 639ac21a01b..978c1b53809 100644--- a/apps/desktop/src/store/connection-request.ts+++ b/apps/desktop/src/store/connection-request.ts@@ -110,7 +110,7 @@ const targetState = oneOf(TARGET_STATES)const targetAction = oneOf(ACTIONS)const settleReason = oneOf(SETTLE_REASONS)-function parseTarget(entry: ConnectionOperationTarget): ConnectionTarget | null {+export function parseConnectionTarget(entry: ConnectionOperationTarget): ConnectionTarget | null {const name = entry.name.trim()if (!name) {@@ -142,7 +142,9 @@ export function normalizeConnectionRequest(return null}- const targets = payload.targets.map(parseTarget).filter((target): target is ConnectionTarget => target !== null)+ const targets = payload.targets+ .map(parseConnectionTarget)+ .filter((target): target is ConnectionTarget => target !== null)if (!payload.op_id || !payload.tool_call_id || !(payload.deadline_at > 0) || targets.length === 0) {return nulldiff --git a/apps/desktop/src/store/mcp-health.ts b/apps/desktop/src/store/mcp-health.tsindex d3ca78ffdaa..c792825f9ce 100644--- a/apps/desktop/src/store/mcp-health.ts+++ b/apps/desktop/src/store/mcp-health.ts@@ -97,12 +97,8 @@ let sweepQueued = falselet offGatewayState: (() => void) | null = nulllet offProfile: (() => void) | null = null-// Navigation only — never auto-launch an OAuth flow from the background. The-// server query param routes through useDeepLinkHighlight on the MCP tab, which-// scrolls to and focuses the server so its ServerConfig pane (with the-// Authenticate button) is one click away.function openMcpServerPage(name: string): void {- window.location.hash = `#/capabilities?tab=mcp&server=${encodeURIComponent(name)}`+ window.location.hash = `#/capabilities?tab=connectors&server=${encodeURIComponent(name)}`}// "Disable" from the toast: `enabled: false` in config.yaml (the server staysdiff --git a/apps/desktop/src/types/hermes.ts b/apps/desktop/src/types/hermes.tsindex 6ff7f883bb0..dc289e939ad 100644--- a/apps/desktop/src/types/hermes.ts+++ b/apps/desktop/src/types/hermes.ts@@ -1657,6 +1657,7 @@ export interface McpServerTestResponse {export interface McpCatalogEntry {name: stringdescription: string+ connector_slug?: string | nullsource: stringtransport: stringauth_type: stringdiff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex 211f614dd07..445fd50a202 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -3700,6 +3700,7 @@ export interface McpCatalogResult {export interface McpCatalogEntry {name: stringdescription: string+ connector_slug?: string | nullinstalled: booleanenabled: booleanrequires: string[]@@ -3720,7 +3721,10 @@ export interface McpServerSummary {oauth_tokens_present?: boolean | nullenabled: booleantools?: unknown | null+ source: McpServerSource+ plugin?: string | null}+export type McpServerSource = 'config' | 'plugin'export interface McpServersStatusResult {servers: McpServerRuntimeRow[]checked_at: number@@ -3733,6 +3737,8 @@ export interface McpServerRuntimeRow {connected: booleandisabled: booleanstatus: McpRuntimeStatus+ source: McpServerSource+ plugin?: string | null}export type McpRuntimeStatus = 'connected' | 'disabled' | 'connecting' | 'failed' | 'lazy' | 'configured'/** ``preset`` (catalog id) and/or ``config`` (url/command/args/env/headers/auth/tools); a ``bearer_token`` is written to the profile's .env, only the header template persists. */diff --git a/apps/shared/src/gateway-contract.openrpc.json b/apps/shared/src/gateway-contract.openrpc.jsonindex cec85af8cf5..bbf0f51f18c 100644--- a/apps/shared/src/gateway-contract.openrpc.json+++ b/apps/shared/src/gateway-contract.openrpc.json@@ -15139,6 +15139,18 @@"title": "Description","type": "string"},+ "connector_slug": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Connector Slug"+ },"installed": {"title": "Installed","type": "boolean"@@ -15627,6 +15639,21 @@},"status": {"$ref": "#/components/schemas/McpRuntimeStatus"+ },+ "source": {+ "$ref": "#/components/schemas/McpServerSource"+ },+ "plugin": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Plugin"}},"required": [@@ -15635,11 +15662,20 @@"tools","connected","disabled",- "status"+ "status",+ "source"],"title": "McpServerRuntimeRow","type": "object"},+ "McpServerSource": {+ "enum": [+ "config",+ "plugin"+ ],+ "title": "McpServerSource",+ "type": "string"+ },"McpServerStatus": {"additionalProperties": true,"properties": {@@ -15775,6 +15811,21 @@],"default": null,"title": "Tools"+ },+ "source": {+ "$ref": "#/components/schemas/McpServerSource"+ },+ "plugin": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "default": null,+ "title": "Plugin"}},"required": [@@ -15782,7 +15833,8 @@"transport","args","env",- "enabled"+ "enabled",+ "source"],"title": "McpServerSummary","type": "object"diff --git a/hermes_cli/mcp_catalog.py b/hermes_cli/mcp_catalog.pyindex 0455270faf2..7546ddfe9ab 100644--- a/hermes_cli/mcp_catalog.py+++ b/hermes_cli/mcp_catalog.py@@ -111,6 +111,7 @@ class CatalogEntry:source: strtransport: TransportSpecauth: AuthSpec+ connector_slug: Optional[str] = Nonetools: ToolsSpec = field(default_factory=ToolsSpec)install: Optional[InstallSpec] = Nonepost_install: str = ""@@ -259,6 +260,14 @@ def _parse_suggest(path: Path, suggest_raw: Any) -> Optional[SuggestSpec]:applications=applications, examples=examples, requires_app=requires_app)+def _parse_connector_slug(path: Path, value: Any) -> Optional[str]:+ if value is None:+ return None+ if not isinstance(value, str) or not re.fullmatch(r"[a-z0-9][a-z0-9_-]*", value):+ raise CatalogError(f"{path}: connector_slug must be a hosted connector slug")+ return value++def _parse_install(path: Path, install_raw: Any) -> Optional[InstallSpec]:if install_raw is None:return None@@ -301,10 +310,11 @@ def _parse_manifest(path: Path) -> CatalogEntry:auth = _parse_auth(path, data.get("auth"), name, transport.type == "http")tools = _parse_tools(path, data.get("tools"))suggest = _parse_suggest(path, data.get("suggest"))+ connector_slug = _parse_connector_slug(path, data.get("connector_slug"))install = _parse_install(path, data.get("install"))return CatalogEntry(name=name, description=description, source=str(data.get("source") or "").strip(),- transport=transport, auth=auth, tools=tools, install=install,+ transport=transport, auth=auth, connector_slug=connector_slug, tools=tools, install=install,post_install=str(data.get("post_install") or ""), suggest=suggest, manifest_path=path,)diff --git a/hermes_cli/plugins.py b/hermes_cli/plugins.pyindex 63b180025ae..db2c6a32cf4 100644--- a/hermes_cli/plugins.py+++ b/hermes_cli/plugins.py@@ -1188,6 +1188,7 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):self._system_prompt_sections: Dict[str, PluginSystemPromptSection] = {}self._plugin_skills: Dict[str, Dict[str, Any]] = {}self._portable_mcp_servers: Dict[str, Dict[str, Any]] = {}+ self._portable_mcp_server_plugins: Dict[str, str] = {}self._aux_tasks: Dict[str, Dict[str, Any]] = {}self._approval_transports: Dict[str, Any] = {}self._slack_action_handlers: List[tuple] = []@@ -1533,6 +1534,9 @@ class PluginManager(PluginLoaderMixin, PluginDispatchMixin, PluginLedgerMixin):"""Return a defensive copy of enabled portable MCP server configs."""return {name: dict(config) for name, config in self._portable_mcp_servers.items()}+ def get_portable_mcp_server_plugins(self) -> Dict[str, str]:+ return dict(self._portable_mcp_server_plugins)+def remove_plugin_skill(self, qualified_name: str) -> None:"""Remove a stale registry entry (silently ignores missing keys)."""self._plugin_skills.pop(qualified_name, None)diff --git a/hermes_cli/plugins_ledger.py b/hermes_cli/plugins_ledger.pyindex e1603683e39..9577f0aec6c 100644--- a/hermes_cli/plugins_ledger.py+++ b/hermes_cli/plugins_ledger.py@@ -289,7 +289,7 @@ class PluginLedgerMixin:self._ownership_ledger, self._plugins, self._hooks, self._middleware,self._plugin_tool_names, self._plugin_platform_names, self._cli_commands,self._plugin_commands, self._plugin_skills, self._portable_mcp_servers,- self._aux_tasks, self._system_prompt_sections, self._approval_transports,+ self._portable_mcp_server_plugins, self._aux_tasks, self._system_prompt_sections, self._approval_transports,self._slack_action_handlers, self._predeclared_modules, self._predeclared_tools,self._platform_handler_factories,):diff --git a/hermes_cli/plugins_loader.py b/hermes_cli/plugins_loader.pyindex 38810c044fc..0b7ea5acc4d 100644--- a/hermes_cli/plugins_loader.py+++ b/hermes_cli/plugins_loader.py@@ -529,6 +529,7 @@ class PluginLoaderMixin:logger.warning("Agent Plugin '%s' MCP server collision: %s", lookup_key, internal_name)continueself._portable_mcp_servers[internal_name] = dict(config)+ self._portable_mcp_server_plugins[internal_name] = lookup_keyloaded.enabled = Trueexcept (Exception, SystemExit) as exc:loaded.error = _load_error_text(exc)diff --git a/hermes_cli/web_routers/mcp.py b/hermes_cli/web_routers/mcp.pyindex 4eab73b1dd3..f4045a49da6 100644--- a/hermes_cli/web_routers/mcp.py+++ b/hermes_cli/web_routers/mcp.py@@ -95,9 +95,16 @@ def _mcp_install_action_name(name: str) -> str:async def list_mcp_servers(profile: Optional[str] = None):from hermes_cli.mcp_config import _get_mcp_servers- # ``url`` may carry a ``${VAR}`` ref — expand it against the requested profile, not this process.- servers = await asyncio.to_thread(_secret_scoped(profile, _get_mcp_servers))- return {"servers": [_mcp_server_summary(name, cfg) for name, cfg in sorted(servers.items())]}+ def _read():+ config_servers = _get_mcp_servers()+ from tui_gateway.mcp_rpc_helpers import server_configs_with_sources++ return server_configs_with_sources(config_servers)++ servers, plugins = await asyncio.to_thread(_secret_scoped(profile, _read))+ return {"servers": [+ _mcp_server_summary(name, cfg, plugins[name]) for name, cfg in sorted(servers.items())+ ]}@router.post("/api/mcp/servers")@@ -114,7 +121,15 @@ async def add_mcp_server(body: MCPServerCreate, profile: Optional[str] = None):# check sits under the same lock span so a concurrent add can't slip# between check and save.with config_write_scope(body.profile or profile):- if name in _get_mcp_servers():+ config_servers = _get_mcp_servers()+ from tui_gateway.mcp_rpc_helpers import server_configs_with_sources++ servers, plugins = server_configs_with_sources(config_servers)+ if plugin := plugins.get(name):+ raise HTTPException(+ status_code=409, detail=f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified",+ )+ if name in servers:raise HTTPException(status_code=409, detail=f"Server '{name}' already exists")if bearer_token is not None:server_config["headers"] = _save_bearer_auth_token(name, bearer_token)@@ -142,6 +157,12 @@ async def replace_mcp_servers(body: MCPServersReplace, profile: Optional[str] =def _run():with config_write_scope(body.profile or profile):+ from tui_gateway.mcp_rpc_helpers import server_configs_with_sources++ _servers, plugins = server_configs_with_sources({})+ for name in body.servers:+ if plugin := plugins.get(name):+ return False, [f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified"]return _replace_mcp_servers(body.servers)ok, issues = await asyncio.to_thread(_run)@@ -152,10 +173,18 @@ async def replace_mcp_servers(body: MCPServersReplace, profile: Optional[str] =@router.delete("/api/mcp/servers/{name}")async def remove_mcp_server(name: str, profile: Optional[str] = None):- from hermes_cli.mcp_config import _remove_mcp_server+ from hermes_cli.mcp_config import _get_mcp_servers, _remove_mcp_serverdef _run():with config_write_scope(profile):+ config_servers = _get_mcp_servers()+ from tui_gateway.mcp_rpc_helpers import server_configs_with_sources++ _servers, plugins = server_configs_with_sources(config_servers)+ if plugin := plugins.get(name):+ raise HTTPException(+ status_code=409, detail=f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified",+ )return _remove_mcp_server(name)if not await asyncio.to_thread(_run):@@ -168,7 +197,13 @@ async def test_mcp_server(name: str, profile: Optional[str] = None):"""Connect to the server, list its tools, disconnect."""from hermes_cli.mcp_config import _get_mcp_servers, _oauth_tokens_present, _probe_single_server- servers = await asyncio.to_thread(_secret_scoped(profile, _get_mcp_servers))+ def _read():+ config_servers = _get_mcp_servers()+ from tui_gateway.mcp_rpc_helpers import server_configs_with_sources++ return server_configs_with_sources(config_servers)[0]++ servers = await asyncio.to_thread(_secret_scoped(profile, _read))if name not in servers:raise HTTPException(status_code=404, detail=f"Server '{name}' not found")@@ -224,11 +259,17 @@ async def auth_mcp_server(name: str, request: Request, profile: Optional[str] =def _read():with _profile_secret_scope(profile):- return _get_mcp_servers(), _home()+ config_servers = _get_mcp_servers()+ from tui_gateway.mcp_rpc_helpers import server_configs_with_sources- servers, flow_home = await asyncio.to_thread(_read)+ servers, plugins = server_configs_with_sources(config_servers)+ return servers, plugins, _home()++ servers, plugins, flow_home = await asyncio.to_thread(_read)if name not in servers:raise HTTPException(status_code=404, detail=f"Server '{name}' not found")+ if plugin := plugins.get(name):+ raise HTTPException(status_code=409, detail=f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified")cfg = dict(servers[name])if not cfg.get("url"):raise HTTPException(status_code=400, detail="stdio servers authenticate via env keys, not OAuth")@@ -326,6 +367,13 @@ async def set_mcp_server_enabled(name: str, body: MCPEnabledToggle, profile: Optdef _run():with config_write_scope(body.profile or profile):cfg = load_config()+ from tui_gateway.mcp_rpc_helpers import server_configs_with_sources++ _servers, plugins = server_configs_with_sources(cfg.get("mcp_servers") or {})+ if plugin := plugins.get(name):+ raise HTTPException(+ status_code=409, detail=f"Server '{name}' is provided by plugin '{plugin}' and cannot be modified",+ )servers = cfg.get("mcp_servers")if not isinstance(servers, dict) or name not in servers:raise HTTPException(status_code=404, detail=f"Server '{name}' not found")@@ -345,6 +393,7 @@ def _catalog_entry_json(entry: Any, installed: bool, enabled: bool) -> Dict[str,return {"name": entry.name,"description": entry.description,+ "connector_slug": entry.connector_slug,"source": entry.source,"transport": transport.type,"auth_type": getattr(auth, "type", "none"),diff --git a/hermes_cli/web_server_mcp.py b/hermes_cli/web_server_mcp.pyindex 32f75a3b605..a4cbfbab603 100644--- a/hermes_cli/web_server_mcp.py+++ b/hermes_cli/web_server_mcp.py@@ -81,7 +81,7 @@ def _redact_mcp_env(env: Dict[str, Any]) -> Dict[str, str]:return out-def _mcp_server_summary(name: str, cfg: Dict[str, Any]) -> Dict[str, Any]:+def _mcp_server_summary(name: str, cfg: Dict[str, Any], plugin: str | None = None) -> Dict[str, Any]:transport = "http" if cfg.get("url") else ("stdio" if cfg.get("command") else "unknown")auth = cfg.get("auth")headers = cfg.get("headers") or {}@@ -98,6 +98,8 @@ def _mcp_server_summary(name: str, cfg: Dict[str, Any]) -> Dict[str, Any]:"enabled": cfg.get("enabled", True) is not False,# Tool selection: list of enabled tool names, or None = all."tools": cfg.get("tools"),+ "source": "plugin" if plugin is not None else "config",+ "plugin": plugin,}diff --git a/optional-mcps/airtable/manifest.yaml b/optional-mcps/airtable/manifest.yamlindex c737d2a9233..cfba44f2d06 100644--- a/optional-mcps/airtable/manifest.yaml+++ b/optional-mcps/airtable/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: airtable+connector_slug: airtabledescription: >-Bases, tables, and records from your Airtable workspace.source: https://support.airtable.com/articles/9897799762-using-the-airtable-mcp-serverdiff --git a/optional-mcps/asana/manifest.yaml b/optional-mcps/asana/manifest.yamlindex 50e6ba790d4..57d9ff1b9be 100644--- a/optional-mcps/asana/manifest.yaml+++ b/optional-mcps/asana/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: asana+connector_slug: asanadescription: >-Tasks, projects, and goals from your Asana workspace.source: https://developers.asana.com/docs/integrating-with-asanas-mcp-serverdiff --git a/optional-mcps/atlassian/manifest.yaml b/optional-mcps/atlassian/manifest.yamlindex fb48f84e782..84b7a957745 100644--- a/optional-mcps/atlassian/manifest.yaml+++ b/optional-mcps/atlassian/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: atlassian+connector_slug: jiradescription: >-Jira issues and Confluence pages via Atlassian's hosted remote MCP.source: https://support.atlassian.com/rovo/docs/getting-started-with-the-atlassian-remote-mcp-server/diff --git a/optional-mcps/attio/manifest.yaml b/optional-mcps/attio/manifest.yamlindex 80f50ac360f..b75ef9581e1 100644--- a/optional-mcps/attio/manifest.yaml+++ b/optional-mcps/attio/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: attio+connector_slug: attiodescription: CRM records, lists, and notes in Attio.source: https://attio.com/help/apps/other-apps/using-the-attio-mcp-serverdiff --git a/optional-mcps/betterstack/manifest.yaml b/optional-mcps/betterstack/manifest.yamlindex ca085f6311d..f8f0c40ccec 100644--- a/optional-mcps/betterstack/manifest.yaml+++ b/optional-mcps/betterstack/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: betterstack+connector_slug: better_stack_mcpdescription: 'Better Stack: logs, uptime monitors, incidents, and status pages.'source: https://betterstack.com/docs/getting-started/integrations/mcp/diff --git a/optional-mcps/calendly/manifest.yaml b/optional-mcps/calendly/manifest.yamlindex a5ca67c7d3e..d7087fe233b 100644--- a/optional-mcps/calendly/manifest.yaml+++ b/optional-mcps/calendly/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: calendly+connector_slug: calendlydescription: Scheduling links, events, and invitees from Calendly.source: https://developer.calendly.com/calendly-mcp-serverdiff --git a/optional-mcps/canva/manifest.yaml b/optional-mcps/canva/manifest.yamlindex b4c6459f2a8..e234f4a2085 100644--- a/optional-mcps/canva/manifest.yaml+++ b/optional-mcps/canva/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: canva+connector_slug: canva_mcpdescription: Create, search, and manage Canva designs.source: https://www.canva.dev/docs/mcp/diff --git a/optional-mcps/cloudflare/manifest.yaml b/optional-mcps/cloudflare/manifest.yamlindex 8e8e7ede485..cf461d5a0cd 100644--- a/optional-mcps/cloudflare/manifest.yaml+++ b/optional-mcps/cloudflare/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: cloudflare+connector_slug: cloudflare_mcpdescription: Full Cloudflare API access via the official remote MCP.source: https://developers.cloudflare.com/agents/model-context-protocol/cloudflare/servers-for-cloudflare/diff --git a/optional-mcps/datadog/manifest.yaml b/optional-mcps/datadog/manifest.yamlindex 0cd8541b0c9..8a71258e736 100644--- a/optional-mcps/datadog/manifest.yaml+++ b/optional-mcps/datadog/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: datadog+connector_slug: datadog_mcpdescription: >-Logs, monitors, dashboards, and incidents from Datadog.source: https://docs.datadoghq.com/bits_ai/mcp_server/diff --git a/optional-mcps/dropbox/manifest.yaml b/optional-mcps/dropbox/manifest.yamlindex f1df12d14f5..91074ed6d0a 100644--- a/optional-mcps/dropbox/manifest.yaml+++ b/optional-mcps/dropbox/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: dropbox+connector_slug: dropboxdescription: Search, read, and manage files in Dropbox.source: https://help.dropbox.com/integrations/connect-dropbox-mcp-serverdiff --git a/optional-mcps/figma/manifest.yaml b/optional-mcps/figma/manifest.yamlindex 630f5df9885..b4c58783a4a 100644--- a/optional-mcps/figma/manifest.yaml+++ b/optional-mcps/figma/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: figma+connector_slug: figmadescription: >-Official Figma remote MCP — design context, Code Connect, andwrite-to-canvas via https://mcp.figma.com/mcp (OAuth).diff --git a/optional-mcps/intercom/manifest.yaml b/optional-mcps/intercom/manifest.yamlindex b07a4726cd1..a0480b7e7be 100644--- a/optional-mcps/intercom/manifest.yaml+++ b/optional-mcps/intercom/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: intercom+connector_slug: intercom_mcpdescription: >-Conversations, tickets, and customer data from Intercom.source: https://developers.intercom.com/docs/guides/mcpdiff --git a/optional-mcps/linear/manifest.yaml b/optional-mcps/linear/manifest.yamlindex 0e7988cd3be..2d933a73a28 100644--- a/optional-mcps/linear/manifest.yaml+++ b/optional-mcps/linear/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: linear+connector_slug: lineardescription: Find, create, and update Linear issues, projects, and comments.source: https://linear.app/docs/mcpdiff --git a/optional-mcps/neon/manifest.yaml b/optional-mcps/neon/manifest.yamlindex 8ba6da416cb..1c63c538ea0 100644--- a/optional-mcps/neon/manifest.yaml+++ b/optional-mcps/neon/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: neon+connector_slug: neon_mcpdescription: 'Neon serverless Postgres: projects, branches, and SQL.'source: https://neon.com/docs/ai/neon-mcp-serverdiff --git a/optional-mcps/notion/manifest.yaml b/optional-mcps/notion/manifest.yamlindex 8916b054482..9fed9d14836 100644--- a/optional-mcps/notion/manifest.yaml+++ b/optional-mcps/notion/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: notion+connector_slug: notiondescription: >-Pages and databases from your Notion workspace.source: https://developers.notion.com/docs/mcpdiff --git a/optional-mcps/prisma-postgres/manifest.yaml b/optional-mcps/prisma-postgres/manifest.yamlindex e90ab17c793..8dfd8ac68c7 100644--- a/optional-mcps/prisma-postgres/manifest.yaml+++ b/optional-mcps/prisma-postgres/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: prisma-postgres+connector_slug: prismadescription: Create and manage Prisma Postgres databases.source: https://www.prisma.io/docs/postgres/integrations/mcp-serverdiff --git a/optional-mcps/railway/manifest.yaml b/optional-mcps/railway/manifest.yamlindex 271675b19b2..e9fee19ba6e 100644--- a/optional-mcps/railway/manifest.yaml+++ b/optional-mcps/railway/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: railway+connector_slug: railwaydescription: 'Railway: projects, services, deployments, and environments.'source: https://docs.railway.com/guides/mcp-serverdiff --git a/optional-mcps/sentry/manifest.yaml b/optional-mcps/sentry/manifest.yamlindex 6ab88bd18e9..c1bf7c8308c 100644--- a/optional-mcps/sentry/manifest.yaml+++ b/optional-mcps/sentry/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: sentry+connector_slug: sentry_mcpdescription: >-Issues, stack traces, and error context from Sentry.source: https://docs.sentry.io/product/sentry-mcp/diff --git a/optional-mcps/stripe/manifest.yaml b/optional-mcps/stripe/manifest.yamlindex 11b8e69c787..144bdde486f 100644--- a/optional-mcps/stripe/manifest.yaml+++ b/optional-mcps/stripe/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: stripe+connector_slug: stripe_mcpdescription: >-Payments, customers, and invoices via Stripe's hosted MCP.source: https://docs.stripe.com/mcpdiff --git a/optional-mcps/supabase/manifest.yaml b/optional-mcps/supabase/manifest.yamlindex 69824671c53..d9a48883de8 100644--- a/optional-mcps/supabase/manifest.yaml+++ b/optional-mcps/supabase/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: supabase+connector_slug: supabasedescription: >-Database, auth, and storage from your Supabase projects.source: https://supabase.com/docs/guides/ai-tools/mcpdiff --git a/optional-mcps/todoist/manifest.yaml b/optional-mcps/todoist/manifest.yamlindex a662a6ded54..7bb2d5b3211 100644--- a/optional-mcps/todoist/manifest.yaml+++ b/optional-mcps/todoist/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: todoist+connector_slug: todoistdescription: Manage Todoist tasks and projects.source: https://www.todoist.com/help/articles/todoist-mcp-serverdiff --git a/optional-mcps/vercel/manifest.yaml b/optional-mcps/vercel/manifest.yamlindex 8d8772a6e4f..2747740523f 100644--- a/optional-mcps/vercel/manifest.yaml+++ b/optional-mcps/vercel/manifest.yaml@@ -3,6 +3,7 @@manifest_version: 1name: vercel+connector_slug: vercel_mcpdescription: >-Deployments, logs, and projects via Vercel's hosted MCP.source: https://vercel.com/docs/mcpdiff --git a/tests/hermes_cli/test_mcp_catalog.py b/tests/hermes_cli/test_mcp_catalog.pyindex 5f8e3c8ca05..2a5c79b1c67 100644--- a/tests/hermes_cli/test_mcp_catalog.py+++ b/tests/hermes_cli/test_mcp_catalog.py@@ -122,6 +122,16 @@ class TestManifestParsing:assert e.auth.type == "none"assert e.install is Noneassert e.suggest is None+ assert e.connector_slug is None++ def test_connector_slug_metadata_reaches_the_catalog_payload(self, catalog_dir):+ from hermes_cli.mcp_catalog import _parse_manifest+ from hermes_cli.web_routers.mcp import _catalog_entry_json++ path = _write_manifest(catalog_dir, "demo", _basic_manifest(connector_slug="demo-connector"))+ entry = _parse_manifest(path)++ assert _catalog_entry_json(entry, False, False)["connector_slug"] == "demo-connector"def test_suggest_block_parsed_and_normalized(self, catalog_dir):_write_manifest(@@ -976,6 +986,17 @@ class TestShippedCatalog:# Asana matches the registered redirect URL exactly; the callback must be pinned.assert cfg["oauth"]["redirect_host"] and cfg["oauth"]["redirect_port"]+ def test_manifest_connector_slugs_are_valid_and_unique(self, monkeypatch):+ from hermes_cli.mcp_catalog import catalog_diagnostics, list_catalog++ source_catalog = Path(__file__).parents[2] / "optional-mcps"+ monkeypatch.setattr("hermes_cli.mcp_catalog._catalog_root", lambda: source_catalog)+ slugs = [entry.connector_slug for entry in list_catalog() if entry.connector_slug is not None]++ assert catalog_diagnostics() == []+ assert slugs+ assert len(slugs) == len(set(slugs))+def test_all_shipped_manifests_parse(self, monkeypatch):"""Every manifest in optional-mcps/ must parse cleanly.diff --git a/tests/tui_gateway/test_mcp_profile_rpcs.py b/tests/tui_gateway/test_mcp_profile_rpcs.pyindex 88f9f947ffb..ca1b7f6a567 100644--- a/tests/tui_gateway/test_mcp_profile_rpcs.py+++ b/tests/tui_gateway/test_mcp_profile_rpcs.py@@ -136,6 +136,8 @@ def test_status_is_profile_scoped_and_credential_safe(hermes_root):"connected": False,"disabled": False,"status": "configured",+ "source": "config",+ "plugin": None,}]assert "error" not in str(payload)diff --git a/tui_gateway/contracts/tools_mcp_plugins.py b/tui_gateway/contracts/tools_mcp_plugins.pyindex 10d8de2dcbf..4ec4a16f3e3 100644--- a/tui_gateway/contracts/tools_mcp_plugins.py+++ b/tui_gateway/contracts/tools_mcp_plugins.py@@ -341,6 +341,7 @@ method("learning.edit", params=LearningEditParams, result=LearningMutationResultclass McpCatalogEntry(Result):name: strdescription: str+ connector_slug: str | None = Noneinstalled: boolenabled: boolrequires: list[str]@@ -355,6 +356,11 @@ method("mcp.catalog", params=ProfileParams, result=McpCatalogResult,doc="Curated MCP presets with per-profile installed/enabled state and the env keys each needs.")+class McpServerSource(WireEnum):+ config = "config"+ plugin = "plugin"++class McpServerSummary(Result):"""``tui_gateway/mcp_rpc_helpers.summarize_server`` — a server's config without secret values."""@@ -368,6 +374,8 @@ class McpServerSummary(Result):oauth_tokens_present: bool | None = Noneenabled: booltools: JsonValue | None = None+ source: McpServerSource+ plugin: str | None = Noneclass McpServersListResult(Result):@@ -396,6 +404,8 @@ class McpServerRuntimeRow(Result):connected: booldisabled: boolstatus: McpRuntimeStatus+ source: McpServerSource+ plugin: str | None = Noneclass McpServersStatusResult(Result):diff --git a/tui_gateway/mcp_rpc_helpers.py b/tui_gateway/mcp_rpc_helpers.pyindex 013a5133bc1..2102a01ce72 100644--- a/tui_gateway/mcp_rpc_helpers.py+++ b/tui_gateway/mcp_rpc_helpers.py@@ -6,15 +6,30 @@ bodies in methods_tools resolve it.from __future__ import annotations-from typing import Any, Dict+from typing import Any, Dict, Mapping-def summarize_server(name: str, cfg: dict) -> Dict[str, Any]:- """Serialize one server's config for a UI (no secret values).+def server_configs_with_sources(config_servers: Mapping[str, dict]) -> tuple[Dict[str, dict], Dict[str, str | None]]:+ servers = {name: dict(cfg) for name, cfg in config_servers.items() if isinstance(cfg, dict)}+ plugins: Dict[str, str | None] = {name: None for name in servers}+ try:+ from hermes_cli.plugins import discover_plugins, get_plugin_manager+ from tools.mcp_tool_config import _filter_suspicious_mcp_servers- Mirrors web_server._mcp_server_summary plus ``oauth_tokens_present`` so a UI can- tell an OAuth server that still needs authentication from one already authenticated.- """+ discover_plugins()+ manager = get_plugin_manager()+ portable = _filter_suspicious_mcp_servers(manager.get_portable_mcp_servers())+ owners = manager.get_portable_mcp_server_plugins()+ for name, cfg in portable.items():+ if name not in servers:+ servers[name] = dict(cfg)+ plugins[name] = owners.get(name)+ except Exception:+ pass+ return servers, plugins+++def summarize_server(name: str, cfg: dict, plugin: str | None = None) -> Dict[str, Any]:from hermes_cli.mcp_config import _oauth_tokens_presentcfg = cfg if isinstance(cfg, dict) else {}@@ -33,7 +48,9 @@ def summarize_server(name: str, cfg: dict) -> Dict[str, Any]:"auth": auth,"oauth_tokens_present": _oauth_tokens_present(name) if auth == "oauth" else None,"enabled": cfg.get("enabled", True) is not False,- "tools": cfg.get("tools")}+ "tools": cfg.get("tools"),+ "source": "plugin" if plugin is not None else "config",+ "plugin": plugin}# ---- BEGIN PLUGIN-COMPAT (revert-scheduled; see COMPAT_MANIFEST.md) ----diff --git a/tui_gateway/methods_tools.py b/tui_gateway/methods_tools.pyindex d34754d41dc..b88988aca65 100644--- a/tui_gateway/methods_tools.py+++ b/tui_gateway/methods_tools.py@@ -111,12 +111,31 @@ def _mcp_rpc(name: str, required=_NAME):return _scoped_rpc(f"mcp.servers.{name}", required=required, catch_resolve=False)+def _mcp_server_rows():+ config_servers = _tools_mod("hermes_cli.mcp_config")._get_mcp_servers()+ return _tools_mod("tui_gateway.mcp_rpc_helpers").server_configs_with_sources(config_servers)++def _mcp_named_server(rid, params):"""(name, servers, None) for a configured server, else (name, servers, 4064 error)."""- name, servers = _str_arg(params, "name"), _tools_mod("hermes_cli.mcp_config")._get_mcp_servers()+ name, servers = _str_arg(params, "name"), _mcp_server_rows()[0]return name, servers, None if name in servers else _err(rid, 4064, f"server '{name}' not found")+def _mcp_plugin_write_error(rid, name: str, plugins: dict):+ plugin = plugins.get(name)+ if plugin is not None:+ return _err(rid, 4090, f"server '{name}' is provided by plugin '{plugin}' and cannot be modified")+ return None+++def _mcp_config_server_or_error(rid, params):+ name, servers, err = _mcp_named_server(rid, params)+ if err:+ return name, servers, err+ return name, servers, _mcp_plugin_write_error(rid, name, _mcp_server_rows()[1])++def _busy_error(rid, session, cmd: str):if session.get("running"):return _err(rid, 4009, busy_message(cmd))@@ -1119,6 +1138,11 @@ def _configure_session_tools(rid, params: dict, sid: str, session) -> dict:toolset_targets = [name for name in targets if ":" not in name and name in valid_toolsets]if toolset_targets:tc._apply_toolset_change(cfg, "cli", toolset_targets, action)+ plugins = _mcp_server_rows()[1]+ for target in mcp_targets:+ server_name = target.split(":", 1)[0]+ if err := _mcp_plugin_write_error(rid, server_name, plugins):+ return errmissing_servers = tc._apply_mcp_change(cfg, mcp_targets, action) if mcp_targets else set()hc.save_config(cfg)info = _reset_session_agent(sid, session) if session else None@@ -1262,6 +1286,7 @@ def _(rid, params: dict) -> dict:transport = getattr(entry, "transport", None) # TransportSpec → its kind stringout.append({"name": entry.name, "description": getattr(entry, "description", "") or "",+ "connector_slug": getattr(entry, "connector_slug", None),"installed": bool(mcp_catalog.is_installed(entry.name)),"enabled": bool(mcp_catalog.is_enabled(entry.name)), "requires": requires,"transport": str(getattr(transport, "kind", "") or transport or "stdio")})@@ -1272,8 +1297,10 @@ def _(rid, params: dict) -> dict:def _(rid, params: dict) -> dict:"""``{servers: [{name, transport, url, command, args, env (key names), auth, oauth_tokens_present,enabled, tools}]}``"""- servers = _tools_mod("hermes_cli.mcp_config")._get_mcp_servers()- return _ok(rid, {"servers": [_mcp_summarize_server(name, cfg) for name, cfg in sorted(servers.items())]})+ servers, plugins = _mcp_server_rows()+ return _ok(rid, {"servers": [+ _mcp_summarize_server(name, cfg, plugins[name]) for name, cfg in sorted(servers.items())+ ]})@_mcp_rpc("status", required=())@@ -1283,13 +1310,15 @@ def _(rid, params: dict) -> dict:scoped profile's; otherwise it is shown only when ``profile`` is the launch profile."""import timehc = _tools_mod("hermes_constants")- configured = _tools_mod("hermes_cli.mcp_config")._get_mcp_servers()+ configured, plugins = _mcp_server_rows()include_runtime = (_tools_mod("agent.secret_scope").is_multiplex_active()or hc.hermes_home_key() == hc.hermes_home_key(hc.get_process_hermes_home()))safe = ("name", "transport", "tools", "connected", "disabled", "status")servers = _tools_mod("tools.mcp_tool_discovery").get_mcp_status(configured, include_runtime=include_runtime)- return _ok(rid, {"servers": [{k: e[k] for k in safe if k in e} for e in servers],- "checked_at": int(time.time() * 1000)})+ return _ok(rid, {"servers": [+ {**{k: e[k] for k in safe if k in e}, "source": "plugin" if plugins[e["name"]] is not None else "config",+ "plugin": plugins[e["name"]]} for e in servers+ ], "checked_at": int(time.time() * 1000)})@_mcp_rpc("add")@@ -1298,7 +1327,10 @@ def _(rid, params: dict) -> dict:tools); ``bearer_token`` goes to the profile's .env (only the header template persists). Dup → 4090."""mc = _tools_mod("hermes_cli.mcp_config")name, preset = _str_arg(params, "name"), _str_arg(params, "preset")- if name in mc._get_mcp_servers():+ servers, plugins = _mcp_server_rows()+ if err := _mcp_plugin_write_error(rid, name, plugins):+ return err+ if name in servers:return _err(rid, 4090, f"server '{name}' already exists")raw_cfg = params.get("config")server_config: dict = dict(raw_cfg) if isinstance(raw_cfg, dict) else {}@@ -1321,7 +1353,7 @@ def _(rid, params: dict) -> dict:"""Secret → profile .env under ``env_var`` (default ``MCP_<NAME>_API_KEY``); config.yaml gets onlya ``${ENV}`` reference (Bearer header for http, ``env`` entry for stdio)."""hc, mc = _tools_mod("hermes_cli.config"), _tools_mod("hermes_cli.mcp_config")- name, servers, err = _mcp_named_server(rid, params)+ name, servers, err = _mcp_config_server_or_error(rid, params)if err:return errvalue = params.get("value")@@ -1382,6 +1414,8 @@ def _(rid, params: dict) -> dict:def _(rid, params: dict) -> dict:"""Remove a server from the profile's config.yaml → ``{ok: true, removed: true}``."""name = _str_arg(params, "name")+ if err := _mcp_plugin_write_error(rid, name, _mcp_server_rows()[1]):+ return errif not _tools_mod("hermes_cli.mcp_config")._remove_mcp_server(name):return _err(rid, 4064, f"server '{name}' not found")return _ok(rid, {"ok": True, "removed": True})@@ -1395,7 +1429,7 @@ def _(rid, params: dict) -> dict:on different machines). Runs on the RPC pool (_LONG_HANDLERS)."""client_redirect_uri = _str_arg(params, "client_redirect_uri") or Nonetry:- name, servers, err = _mcp_named_server(rid, params)+ name, servers, err = _mcp_config_server_or_error(rid, params)if err:return errcfg = dict(servers[name])