Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

40.8 KB
Raw Blame
import {
  AGENT_REGISTRY,
  type AgentId,
  type AgentMode,
  type ApplyIntent,
  agentIdForHandoffTarget,
  agentIdForTerminalCli,
  CONNECTION_ROW_AGENT_IDS,
  type HandoffHostPlatform,
  type HostSnapshot,
  isHandoffTargetSupportedOn,
} from '@inkeep/open-knowledge-core/agent-registry';
import {
  type HandoffTarget,
  TERMINAL_CLI_IDS,
  TERMINAL_CLIS,
  type TerminalCli,
} from '@inkeep/open-knowledge-core/handoff';
import { useLingui } from '@lingui/react/macro';
import { useQuery } from '@tanstack/react-query';
import { ArrowUpRight, Check, Search, TriangleAlert, WifiOff } from 'lucide-react';
import { type ReactNode, useEffect, useEffectEvent, useRef, useState } from 'react';
import { RegisteredAgentIcon } from '@/components/acp/RegisteredAgentIcon';
import {
  setSetupPromptDismissed,
  setupPromptDismissed,
} from '@/components/handoff/ExternalHandoffGate';
import { TargetIcon } from '@/components/handoff/OpenInAgentMenuItem';
import { useTerminalLaunch } from '@/components/handoff/TerminalLaunchContext';
import { cliIconTargetId } from '@/components/handoff/terminal-cli-display';
import { useInstalledAgents } from '@/components/handoff/useInstalledAgents';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Spinner } from '@/components/ui/spinner';
import { Switch } from '@/components/ui/switch';
import {
  isDesktopTargetEnabled,
  isInAppAgentEnabled,
  isTerminalCliRowEnabled,
} from '@/lib/acp/agent-visibility';
import {
  type CatalogAgent,
  fetchAgentCatalog,
  harnessPresenceRank,
  isHarnessDetected,
} from '@/lib/acp/catalog';
import {
  desktopEnabledKey,
  type EnabledOverrides,
  inAppEnabledKey,
  setAgentEnabled,
  terminalEnabledKey,
  useEnabledOverrides,
} from '@/lib/acp/enabled-agents';
import {
  type RegisteredAgent,
  reassignDefaultIfDisabled,
  registerAgent,
  useRegisteredAgents,
} from '@/lib/acp/registered-agents';
import {
  type ApplyAgentConnectionsResult,
  applyAgentConnectionIntents,
} from '@/lib/agent-connections';
import { followupHintText } from '@/lib/agent-followup-hint';
import { isTargetOfferedOnHost, VISIBLE_TARGETS } from '@/lib/handoff/targets';
import { useWorkspace } from '@/lib/use-workspace';
import {
  type ApplyConnections,
  allAvailableCellsChecked,
  ConfigureConnectionDialog,
  ConnectionAgentIcon,
  connectionLabel,
  connectionsFromSnapshot,
  hasConfigurableCell,
  hasPairedConnectionRows,
  installedCount,
  intentsForParts,
  partsForConnection,
  RemoveConnectionDialog,
  removalIntents,
} from './AgentConnectionDialogs';
import {
  deriveRowConnectionStatus,
  deriveRowFollowup,
  followupRowFamily,
  type RowConnectionStatus,
  type RowPresence,
  resolvePresence,
} from './agent-connection-status';
import { type RowAction, rowActionFor, rowHasResidualFiles } from './agent-row-action';
import { groupHeadingFor } from './group-heading';
import { SettingsSectionHeader } from './SettingsSectionHeader';
import { AGENT_CONNECTIONS_SECTION_LABEL } from './settings-section-labels';

function AgentRow({
  icon,
  name,
  hint,
  status,
  action,
  checked,
  disabled,
  ariaLabel,
  testId,
  rowTestId,
  statusId,
  onToggle,
}: {
  icon: ReactNode;
  name: ReactNode;
  hint?: { text: ReactNode; action?: ReactNode };
  status?: ReactNode;
  action?: ReactNode;
  checked?: boolean;
  disabled?: boolean;
  ariaLabel: string;
  testId: string;
  rowTestId: string;
  statusId?: string;
  onToggle?: (next: boolean) => void;
}): ReactNode {
  const hintId = hint ? `${rowTestId}-hint` : undefined;
  return (
    <div className="flex items-center justify-between gap-3 px-3 py-2.5" data-testid={rowTestId}>
      <div className="flex min-w-0 items-start gap-2.5">
        <span className="flex h-5 shrink-0 items-center">{icon}</span>
        <div className="flex min-w-0 flex-col">
          <span className="truncate text-sm leading-5">{name}</span>
          {hint ? (
            <span className="flex min-w-0 items-center gap-1.5">
              <span id={hintId} className="truncate text-muted-foreground text-1sm">
                {hint.text}
              </span>
              {hint.action}
            </span>
          ) : null}
          {status ? <span id={statusId}>{status}</span> : null}
        </div>
      </div>
      <div className="flex shrink-0 items-center gap-2">
        {action}
        {onToggle === undefined ? null : (
          <Switch
            checked={checked ?? false}
            disabled={disabled}
            onCheckedChange={onToggle}
            aria-label={ariaLabel}
            aria-describedby={[hintId, statusId].filter(Boolean).join(' ') || undefined}
            data-testid={testId}
          />
        )}
      </div>
    </div>
  );
}

function ResetHandoffSetupPrompt({
  target,
  projectDir,
  displayName,
}: {
  target: HandoffTarget;
  projectDir: string;
  displayName: string;
}): ReactNode {
  const { t } = useLingui();
  const [dismissed, setDismissed] = useState(() => setupPromptDismissed(target, projectDir));
  if (!dismissed) return null;
  return (
    <Button
      variant="ghost"
      size="sm"
      className="shrink-0 font-mono uppercase"
      aria-label={t`Show prompts again for ${displayName} in this project`}
      onClick={() => {
        setSetupPromptDismissed(target, projectDir, false);
        setDismissed(setupPromptDismissed(target, projectDir));
      }}
    >
      {t`Show prompts again`}
    </Button>
  );
}

function isToggleLocked(presence: RowPresence, enabled: boolean): boolean {
  return presence === 'absent' && !enabled;
}

function AgentGroup({
  label,
  labelIcon,
  subtitle,
  children,
  labelId,
}: {
  label: string;
  labelIcon?: ReactNode;
  subtitle?: ReactNode;
  labelId: string;
  children: ReactNode;
}): ReactNode {
  return (
    <section aria-labelledby={labelId}>
      <div className="mb-2">
        <h4
          id={labelId}
          tabIndex={-1}
          className="flex items-center gap-1.5 font-mono text-muted-foreground text-xs uppercase tracking-wide"
        >
          {label}
          {labelIcon}
        </h4>
        {subtitle ? <p className="mt-1 text-muted-foreground text-xs">{subtitle}</p> : null}
      </div>
      <div className="divide-y overflow-hidden rounded-md border">{children}</div>
    </section>
  );
}

function restoreGroupFocusOnRemoval(button: HTMLButtonElement | null) {
  if (!button) return;
  return () => {
    if (button.ownerDocument.activeElement === button) {
      groupHeadingFor(button)?.focus();
    }
  };
}

function FoldToggleButton({
  hiddenCount,
  expanded,
  onToggle,
  testId,
}: {
  hiddenCount: number;
  expanded: boolean;
  onToggle: () => void;
  testId: string;
}): ReactNode {
  const { t } = useLingui();
  if (hiddenCount <= 0) return null;
  return (
    <Button
      ref={restoreGroupFocusOnRemoval}
      type="button"
      variant="ghost"
      onClick={onToggle}
      aria-expanded={expanded}
      className="w-full justify-center rounded-none font-normal text-1sm text-muted-foreground"
      data-testid={testId}
    >
      {expanded ? t`Show less` : t`Show ${hiddenCount} more`}
    </Button>
  );
}

function ConnectionStatusLine({
  status,
  enabled,
}: {
  status: RowConnectionStatus;
  enabled: boolean;
}): ReactNode {
  const { t } = useLingui();
  if (status === 'connected') {
    return (
      <span className="mt-0.5 inline-flex items-center gap-1 text-muted-foreground text-xs">
        <Check aria-hidden className="size-3.5" />
        {t`Connected`}
      </span>
    );
  }
  if (status === 'not-connected' && enabled) {
    return (
      <span className="mt-0.5 inline-flex items-center gap-1 text-warning text-xs">
        <TriangleAlert aria-hidden className="size-3.5" />
        {t`Not connected`}
      </span>
    );
  }
  return null;
}

function RowActionButton({
  action,
  rowLabel,
  describedById,
  onConfigure,
  onRemove,
}: {
  action: RowAction;
  describedById?: string;
  rowLabel: string;
  onConfigure: () => void;
  onRemove: () => void;
}): ReactNode {
  const { t } = useLingui();
  switch (action.kind) {
    case 'none':
      return null;
    case 'install':
      return (
        <Button variant="link" size="sm" className="shrink-0" asChild>
          <a
            href={action.url}
            target="_blank"
            rel="noreferrer"
            aria-label={t`Install ${rowLabel}`}
            aria-describedby={describedById}
          >
            {t`Install`}
            <ArrowUpRight aria-hidden />
          </a>
        </Button>
      );
    case 'setup-doc':
      return (
        <Button variant="link" size="sm" className="shrink-0" asChild>
          <a
            href={`https://openknowledge.ai/docs/integrations/${action.slug}`}
            target="_blank"
            rel="noreferrer"
            aria-label={t`How to set up ${rowLabel}`}
            aria-describedby={describedById}
          >
            {t`How to set up`}
            <ArrowUpRight aria-hidden />
          </a>
        </Button>
      );
    case 'connect':
      return (
        <Button
          size="sm"
          className="shrink-0 font-mono uppercase"
          onClick={onConfigure}
          aria-label={t`Add MCP & skill for ${rowLabel}`}
          aria-describedby={describedById}
        >
          {t`Add MCP & skill`}
        </Button>
      );
    case 'manage':
      return (
        <Button
          variant="outline"
          size="sm"
          className="shrink-0 font-mono uppercase"
          onClick={onConfigure}
          aria-label={t`Manage ${rowLabel}`}
          aria-describedby={describedById}
        >
          {t`Manage`}
        </Button>
      );
    case 'remove':
      return (
        <Button
          variant="outline"
          size="sm"
          className="shrink-0 font-mono uppercase"
          onClick={onRemove}
          aria-label={t`Remove OpenKnowledge from ${rowLabel}`}
          aria-describedby={describedById}
        >
          {t`Remove`}
        </Button>
      );
  }
}

function InlineRemoveButton({
  rowLabel,
  onRemove,
}: {
  rowLabel: string;
  onRemove: () => void;
}): ReactNode {
  const { t } = useLingui();
  return (
    <Button
      type="button"
      variant="link-muted"
      className="h-auto p-0 text-1sm underline underline-offset-4 hover:text-destructive"
      onClick={onRemove}
      aria-label={t`Remove OpenKnowledge from ${rowLabel}`}
    >
      {t`Remove`}
    </Button>
  );
}

function registryInstallUrl(
  agentId: AgentId | undefined,
  hostPlatform: HandoffHostPlatform | undefined,
): string | null {
  if (agentId === undefined) return null;
  const external = AGENT_REGISTRY[agentId].external;
  if (external === undefined) return null;
  return isHandoffTargetSupportedOn(external, hostPlatform) ? external.installUrl : null;
}

function readProducedFacts(snapshot: HostSnapshot | null): boolean {
  return (
    snapshot !== null &&
    Object.values(snapshot.probes.satisfiers).some(
      (probe) => probe !== undefined && probe.state !== 'unprobed',
    )
  );
}

interface InAppOrdering {
  primaryKeys: ReadonlySet<string>;
  ranks: ReadonlyMap<string, number>;
}

function inAppAgentKey(agent: { source: string; id: string }): string {
  return `${agent.source}:${agent.id}`;
}

function isInAppAgentChecked(
  overrides: EnabledOverrides,
  registeredKeys: ReadonlySet<string>,
  agent: CatalogAgent,
): boolean {
  const isRegistered = registeredKeys.has(inAppAgentKey(agent));
  const isDetected = isHarnessDetected(agent);
  return isInAppAgentEnabled(
    overrides,
    agent.source,
    agent.id,
    isRegistered || isDetected,
    agent.supported,
  );
}

function isPrimaryInAppAgent(
  overrides: EnabledOverrides,
  registeredKeys: ReadonlySet<string>,
  agent: CatalogAgent,
): boolean {
  return (
    (agent.harness !== undefined && harnessPresenceRank(agent) === 0) ||
    isInAppAgentChecked(overrides, registeredKeys, agent)
  );
}

function createInAppOrdering(
  agents: readonly CatalogAgent[],
  overrides: EnabledOverrides,
  registered: readonly RegisteredAgent[],
): InAppOrdering {
  const registeredKeys = new Set(registered.map((agent) => inAppAgentKey(agent)));
  const isPrimary = (agent: CatalogAgent): boolean =>
    isPrimaryInAppAgent(overrides, registeredKeys, agent);
  const ordered = [...agents].sort(
    (a, b) => Number(isPrimary(b)) - Number(isPrimary(a)) || a.name.localeCompare(b.name),
  );
  return {
    primaryKeys: new Set(ordered.filter(isPrimary).map(inAppAgentKey)),
    ranks: new Map(ordered.map((agent, index) => [inAppAgentKey(agent), index])),
  };
}

function extendInAppOrdering(
  ordering: InAppOrdering,
  agents: readonly CatalogAgent[],
  overrides: EnabledOverrides,
  registered: readonly RegisteredAgent[],
): InAppOrdering {
  const unseen = agents.filter((agent) => !ordering.ranks.has(inAppAgentKey(agent)));
  if (unseen.length === 0) return ordering;

  const registeredKeys = new Set(registered.map((agent) => inAppAgentKey(agent)));
  const isPrimary = (agent: CatalogAgent): boolean =>
    isPrimaryInAppAgent(overrides, registeredKeys, agent);
  const unseenPrimary = unseen.filter(isPrimary).sort((a, b) => a.name.localeCompare(b.name));
  const unseenSecondary = unseen
    .filter((agent) => !isPrimary(agent))
    .sort((a, b) => a.name.localeCompare(b.name));
  const existingKeys = [...ordering.ranks.entries()]
    .sort(([, a], [, b]) => a - b)
    .map(([key]) => key);
  const existingPrimary = existingKeys.filter((key) => ordering.primaryKeys.has(key));
  const existingSecondary = existingKeys.filter((key) => !ordering.primaryKeys.has(key));
  const orderedKeys = [
    ...existingPrimary,
    ...unseenPrimary.map(inAppAgentKey),
    ...existingSecondary,
    ...unseenSecondary.map(inAppAgentKey),
  ];

  return {
    primaryKeys: new Set([...ordering.primaryKeys, ...unseenPrimary.map(inAppAgentKey)]),
    ranks: new Map(orderedKeys.map((key, index) => [key, index])),
  };
}

export function AgentConnectionsSection({
  applyConnections = applyAgentConnectionIntents,
}: {
  applyConnections?: ApplyConnections;
} = {}): ReactNode {
  const { t } = useLingui();
  const overrides = useEnabledOverrides();
  const registered = useRegisteredAgents();
  const { states, refresh } = useInstalledAgents();
  const terminalLaunch = useTerminalLaunch();
  const workspace = useWorkspace();
  const [query, setQuery] = useState('');
  const [showInAppOverflow, setShowInAppOverflow] = useState(false);
  const [showTerminalOverflow, setShowTerminalOverflow] = useState(false);
  const [showDesktopOverflow, setShowDesktopOverflow] = useState(false);
  const [snapshot, setSnapshot] = useState<HostSnapshot | null>(null);
  const [readFailed, setReadFailed] = useState(false);
  const [readOnly, setReadOnly] = useState(false);
  const [devBuild, setDevBuild] = useState(false);
  const [reloadInstallState, setReloadInstallState] = useState(0);
  const [configureId, setConfigureId] = useState<AgentId | null>(null);
  const [removeId, setRemoveId] = useState<AgentId | null>(null);
  const switchRevertKey = useRef<string | null>(null);
  const requestVersion = useRef(0);

  const catalog = useQuery({
    queryKey: ['acp-catalog'],
    queryFn: ({ signal }) => fetchAgentCatalog(signal),
    staleTime: 5 * 60 * 1000,
  });
  const [inAppOrdering, setInAppOrdering] = useState<InAppOrdering | null>(() =>
    catalog.data === undefined
      ? null
      : createInAppOrdering(catalog.data.agents, overrides, registered),
  );
  let activeInAppOrdering = inAppOrdering ?? createInAppOrdering([], overrides, registered);
  if (catalog.data !== undefined) {
    const nextInAppOrdering =
      inAppOrdering === null
        ? createInAppOrdering(catalog.data.agents, overrides, registered)
        : extendInAppOrdering(inAppOrdering, catalog.data.agents, overrides, registered);
    if (nextInAppOrdering !== inAppOrdering) setInAppOrdering(nextInAppOrdering);
    activeInAppOrdering = nextInAppOrdering;
  }

  const refreshOnMount = useEffectEvent(() => {
    void refresh();
  });
  useEffect(() => {
    refreshOnMount();
  }, []);

  // biome-ignore lint/correctness/useExhaustiveDependencies: the retry counter re-fires the same read
  useEffect(() => {
    let active = true;
    const version = ++requestVersion.current;
    void applyConnections([])
      .then((result) => {
        if (!active || requestVersion.current !== version) return;
        if (result.snapshot !== null) setSnapshot(result.snapshot);
        setReadFailed(!readProducedFacts(result.snapshot));
        setReadOnly(result.unavailable === true);
        setDevBuild(result.devBuild === true);
      })
      .catch(() => {
        if (active && requestVersion.current === version) setReadFailed(true);
      });
    return () => {
      active = false;
    };
  }, [applyConnections, reloadInstallState]);

  const catalogAgents = catalog.data?.agents;
  const registeredKeys = new Set(registered.map((agent) => inAppAgentKey(agent)));
  const installedClis = terminalLaunch?.installedClis ?? {};

  const connections = snapshot === null ? [] : connectionsFromSnapshot(snapshot);
  const configureConnection = connections.find((c) => c.id === configureId) ?? null;
  const removeConnection = connections.find((c) => c.id === removeId) ?? null;

  async function applyAndRefresh(
    intents: readonly ApplyIntent[],
  ): Promise<ApplyAgentConnectionsResult> {
    const result = await applyConnections(intents);
    requestVersion.current += 1;
    if (result.snapshot !== null) setSnapshot(result.snapshot);
    setReadFailed(!readProducedFacts(result.snapshot));
    if (result.unavailable === true) setReadOnly(true);
    if (result.devBuild === true) setDevBuild(true);
    return result;
  }

  function rowPresence(agentId: AgentId | undefined, detected: boolean | null): RowPresence {
    if (detected === false) return 'absent';
    if (detected === true) return 'present';
    return agentId === undefined ? 'unknown' : resolvePresence(agentId, snapshot, detected);
  }

  const terminalRowAgentIds = new Set<AgentId>(
    TERMINAL_CLI_IDS.map(agentIdForTerminalCli).filter((id): id is AgentId => id !== undefined),
  );
  const externalRowAgentIds = new Set<AgentId>(
    VISIBLE_TARGETS.map((target) => agentIdForHandoffTarget(target.id)).filter(
      (id): id is AgentId => id !== undefined,
    ),
  );
  function siblingRowPresence(agentId: AgentId, mode: AgentMode): RowPresence {
    if (mode === 'terminal') {
      const targetId = AGENT_REGISTRY[agentId].external?.targetId;
      return targetId === undefined
        ? 'unknown'
        : rowPresence(agentId, states[targetId]?.installed ?? null);
    }
    const cli = TERMINAL_CLI_IDS.find((id) => agentIdForTerminalCli(id) === agentId);
    return cli === undefined ? 'unknown' : rowPresence(agentId, installedClis[cli] ?? null);
  }

  function connectionSlots(
    agentId: AgentId | undefined,
    rowLabel: string,
    rowTestId: string,
    mode: AgentMode,
    enabled: boolean,
    detected: boolean | null,
    presence: RowPresence,
    installUrl?: string | null,
  ): {
    status: ReactNode;
    action: ReactNode;
    hintAction: ReactNode;
    residualFiles: boolean;
    statusId?: string;
  } {
    const connection =
      agentId === undefined ? undefined : connections.find((c) => c.id === agentId);
    if (
      connection === undefined ||
      agentId === undefined ||
      snapshot === null ||
      !readProducedFacts(snapshot)
    ) {
      return {
        status: undefined,
        action: undefined,
        hintAction: undefined,
        residualFiles: false,
        statusId: undefined,
      };
    }
    const actionInput = {
      enabled,
      installedCount: installedCount(partsForConnection(connection)),
      presence,
      configurable: hasConfigurableCell(connection),
      setupDocSlug: connection.row.setupDocSlug,
      installUrl:
        installUrl === undefined
          ? (AGENT_REGISTRY[agentId].external?.installUrl ?? null)
          : installUrl,
    };
    const action = rowActionFor(actionInput);
    const siblingMayBeUsingFiles =
      hasPairedConnectionRows(agentId) && siblingRowPresence(agentId, mode) !== 'absent';
    const residualFiles = rowHasResidualFiles(actionInput) && !siblingMayBeUsingFiles;
    const rowStatus = deriveRowConnectionStatus({ agentId, mode, snapshot, detected });
    const speaks = rowStatus === 'connected' || (rowStatus === 'not-connected' && enabled);
    const statusId = speaks ? `${rowTestId}-status` : undefined;
    const actionable = !readOnly || action.kind === 'install' || action.kind === 'setup-doc';
    const projectMcp = connection.cells.projectMcp;
    const ownsFollowup =
      projectMcp === undefined ||
      !hasPairedConnectionRows(agentId) ||
      followupRowFamily(projectMcp.consentClass) === mode;
    const followup = ownsFollowup
      ? followupHintText(deriveRowFollowup({ agentId, mode, snapshot, detected, projectMcp }))
      : null;
    return {
      status: speaks ? (
        <>
          <ConnectionStatusLine status={rowStatus} enabled={enabled} />
          {followup === null ? null : (
            <span
              className="mt-0.5 block text-muted-foreground text-xs"
              data-testid={`${rowTestId}-followup`}
            >
              {followup}
            </span>
          )}
        </>
      ) : undefined,
      action: actionable ? (
        <RowActionButton
          action={action}
          rowLabel={rowLabel}
          describedById={statusId}
          onConfigure={() => setConfigureId(agentId)}
          onRemove={() => setRemoveId(agentId)}
        />
      ) : undefined,
      hintAction:
        residualFiles && !readOnly ? (
          <InlineRemoveButton rowLabel={rowLabel} onRemove={() => setRemoveId(agentId)} />
        ) : undefined,
      residualFiles,
      statusId,
    };
  }

  function presenceHint(kind: 'not-installed' | 'not-detected', residualFiles: boolean): string {
    if (kind === 'not-installed') {
      return residualFiles ? t`Not installed · OpenKnowledge files present` : t`Not installed`;
    }
    return residualFiles
      ? t`Not detected on this machine · OpenKnowledge files present`
      : t`Not detected on this machine`;
  }

  function toggleConnectable(
    key: string,
    agentId: AgentId | undefined,
    mode: AgentMode,
    next: boolean,
    detected?: boolean | null,
  ): void {
    setAgentEnabled(key, next);
    if (!next || readOnly || agentId === undefined || snapshot === null) return;
    const connection = connections.find((c) => c.id === agentId);
    if (connection === undefined || !hasConfigurableCell(connection)) return;
    if (deriveRowConnectionStatus({ agentId, mode, snapshot, detected }) !== 'not-connected') {
      return;
    }
    switchRevertKey.current = key;
    setConfigureId(agentId);
  }

  function refreshInAppOrdering(): void {
    if (catalogAgents !== undefined) {
      setInAppOrdering(createInAppOrdering(catalogAgents, overrides, registered));
    }
  }

  function updateQuery(nextQuery: string): void {
    if (query.trim() !== '' && nextQuery.trim() === '') refreshInAppOrdering();
    setQuery(nextQuery);
  }

  function toggleInAppOverflow(): void {
    if (showInAppOverflow) refreshInAppOrdering();
    setShowInAppOverflow(!showInAppOverflow);
  }

  const q = query.trim().toLowerCase();
  const matches = (text: string): boolean => q === '' || text.toLowerCase().includes(q);

  const inAppAgents = (catalogAgents ?? []).filter((agent) => matches(agent.name));
  const cliPresent = (cli: TerminalCli): boolean => installedClis[cli] !== false;
  const terminalClis = TERMINAL_CLI_IDS.filter((cli) => {
    const { displayName } = TERMINAL_CLIS[cli];
    return matches(displayName) || matches(t`${displayName} CLI`) || matches(cli);
  }).sort(
    (a, b) =>
      Number(cliPresent(b)) - Number(cliPresent(a)) ||
      TERMINAL_CLIS[a].displayName.localeCompare(TERMINAL_CLIS[b].displayName),
  );
  const desktopPresence = (id: HandoffTarget) =>
    rowPresence(agentIdForHandoffTarget(id), states[id]?.installed ?? null);
  const hostPlatform = typeof window === 'undefined' ? undefined : window.okDesktop?.platform;
  const desktopTargets = VISIBLE_TARGETS.filter((target) => {
    const { displayName } = target;
    return (
      isTargetOfferedOnHost(target, {
        platform: hostPlatform,
        installed: states[target.id]?.installed,
      }) &&
      (matches(t`${displayName} Desktop`) || matches(target.id))
    );
  }).sort(
    (a, b) =>
      Number(desktopPresence(a.id) === 'absent') - Number(desktopPresence(b.id) === 'absent'),
  );

  const canLaunchTerminal = terminalLaunch !== null;

  const rowedElsewhere = new Set<AgentId>([...terminalRowAgentIds, ...externalRowAgentIds]);
  const unlaunchableIds = CONNECTION_ROW_AGENT_IDS.filter(
    (id) => !rowedElsewhere.has(id) && matches(connectionLabel(id)),
  );

  const searching = q !== '';
  const catalogReady = !catalog.isLoading && !catalog.isError;
  const noMatches =
    searching &&
    catalogReady &&
    inAppAgents.length === 0 &&
    terminalClis.length === 0 &&
    desktopTargets.length === 0 &&
    unlaunchableIds.length === 0;
  const showInApp = !searching || catalog.isLoading || catalog.isError || inAppAgents.length > 0;
  const showTerminal = !searching || terminalClis.length > 0;
  const showDesktop = desktopTargets.length > 0 || unlaunchableIds.length > 0;

  const inAppChecked = (agent: CatalogAgent): boolean => {
    return isInAppAgentChecked(overrides, registeredKeys, agent);
  };
  const wasPrimaryAgentAtOrderingBoundary = (agent: CatalogAgent): boolean => {
    return activeInAppOrdering.primaryKeys.has(inAppAgentKey(agent));
  };
  const orderingRank = (agent: CatalogAgent): number => {
    return activeInAppOrdering.ranks.get(inAppAgentKey(agent)) ?? Number.MAX_SAFE_INTEGER;
  };
  const inAppPrimary = inAppAgents.filter(wasPrimaryAgentAtOrderingBoundary);
  const inAppShown = [...(searching || showInAppOverflow ? inAppAgents : inAppPrimary)].sort(
    (a, b) => orderingRank(a) - orderingRank(b) || a.name.localeCompare(b.name),
  );
  const inAppHiddenCount = searching ? 0 : inAppAgents.length - inAppPrimary.length;

  const terminalPrimary = terminalClis.filter(cliPresent);
  const terminalFoldable =
    terminalPrimary.length > 0 && terminalPrimary.length < terminalClis.length;
  const terminalShown =
    !terminalFoldable || searching || showTerminalOverflow ? terminalClis : terminalPrimary;
  const terminalHiddenCount =
    terminalFoldable && !searching ? terminalClis.length - terminalPrimary.length : 0;

  const desktopPrimary = desktopTargets.filter((target) => desktopPresence(target.id) !== 'absent');
  const unlaunchablePrimary = unlaunchableIds.filter(
    (id) =>
      rowPresence(id, connections.find((c) => c.id === id)?.row.detected ?? null) !== 'absent',
  );
  const desktopPrimaryCount = desktopPrimary.length + unlaunchablePrimary.length;
  const desktopTotalCount = desktopTargets.length + unlaunchableIds.length;
  const desktopFoldable = desktopPrimaryCount > 0 && desktopPrimaryCount < desktopTotalCount;
  const desktopExpanded = !desktopFoldable || searching || showDesktopOverflow;
  const desktopShown = desktopExpanded ? desktopTargets : desktopPrimary;
  const unlaunchableShown = desktopExpanded ? unlaunchableIds : unlaunchablePrimary;
  const desktopHiddenCount =
    desktopFoldable && !searching ? desktopTotalCount - desktopPrimaryCount : 0;

  const inAppHasDetected = !catalogReady || inAppAgents.some(isHarnessDetected);
  const terminalHasPresent = canLaunchTerminal && terminalClis.some(cliPresent);
  const desktopHasPresent = desktopTargets.some((tg) => states[tg.id]?.installed === true);

  const inAppGroup = showInApp ? (
    <AgentGroup key="in-app" label={t`In app`} labelId="settings-configure-agents-in-app">
      {catalog.isLoading ? (
        <div className="flex items-center justify-center gap-2 px-3 py-6 text-muted-foreground text-sm">
          <Spinner className="size-4" aria-hidden="true" />
          {t`Loading agents…`}
        </div>
      ) : catalog.isError ? (
        <div className="flex flex-col items-center gap-2 px-3 py-6 text-center text-muted-foreground text-sm">
          <WifiOff className="size-5" aria-hidden="true" />
          <span>{t`Couldn't reach the agent registry.`}</span>
          <Button type="button" variant="outline" size="sm" onClick={() => void catalog.refetch()}>
            {t`Try again`}
          </Button>
        </div>
      ) : (catalogAgents?.length ?? 0) === 0 ? (
        <p className="px-3 py-6 text-center text-muted-foreground text-sm">
          {t`No agents available.`}
        </p>
      ) : (
        <>
          {inAppShown.map((agent: CatalogAgent) => {
            const agentKey = inAppAgentKey(agent);
            const checked = inAppChecked(agent);
            const hint = !agent.supported ? t`Not available on this platform` : agent.description;
            return (
              <AgentRow
                key={agentKey}
                icon={
                  <RegisteredAgentIcon
                    agentId={agent.id}
                    iconUrl={agent.iconUrl}
                    className="size-4"
                  />
                }
                name={agent.name}
                hint={hint === undefined ? undefined : { text: hint }}
                checked={checked}
                disabled={!agent.supported}
                ariaLabel={t`Enable ${agent.name}`}
                testId={`configure-agents-in-app-${agentKey}`}
                rowTestId={`configure-agents-in-app-row-${agentKey}`}
                onToggle={(next) => {
                  if (next) {
                    registerAgent(
                      {
                        source: agent.source,
                        id: agent.id,
                        name: agent.name,
                        supported: agent.supported,
                        featured: agent.featured,
                        ...(agent.iconUrl !== undefined ? { iconUrl: agent.iconUrl } : {}),
                      },
                      { makeDefault: false },
                    );
                    setAgentEnabled(inAppEnabledKey(agent.source, agent.id), true);
                  } else {
                    setAgentEnabled(inAppEnabledKey(agent.source, agent.id), false);
                    reassignDefaultIfDisabled(agentKey, (a) =>
                      isInAppAgentEnabled(overrides, a.source, a.id, true, a.supported),
                    );
                  }
                }}
              />
            );
          })}
          <FoldToggleButton
            hiddenCount={inAppHiddenCount}
            expanded={showInAppOverflow}
            onToggle={toggleInAppOverflow}
            testId="configure-agents-in-app-show-more"
          />
        </>
      )}
    </AgentGroup>
  ) : null;

  const terminalGroup = showTerminal ? (
    <AgentGroup key="terminal" label={t`Terminal`} labelId="settings-configure-agents-terminal">
      {terminalShown.map((cli: TerminalCli) => {
        const { displayName } = TERMINAL_CLIS[cli];
        const detected = installedClis[cli] ?? null;
        const presence = rowPresence(agentIdForTerminalCli(cli), detected);
        const enabled = isTerminalCliRowEnabled(overrides, cli, presence === 'absent');
        const rowTestId = `configure-agents-terminal-row-${cli}`;
        const { status, action, hintAction, residualFiles, statusId } = connectionSlots(
          agentIdForTerminalCli(cli),
          t`${displayName} CLI`,
          rowTestId,
          'terminal',
          enabled,
          detected,
          presence,
          registryInstallUrl(agentIdForTerminalCli(cli), hostPlatform) ??
            TERMINAL_CLIS[cli].docsUrl,
        );
        return (
          <AgentRow
            key={cli}
            icon={<TargetIcon id={cliIconTargetId(cli)} className="size-4" aria-hidden="true" />}
            name={t`${displayName} CLI`}
            hint={
              presence === 'absent'
                ? { text: presenceHint('not-installed', residualFiles), action: hintAction }
                : undefined
            }
            status={status}
            action={action}
            checked={enabled}
            disabled={isToggleLocked(presence, enabled)}
            ariaLabel={t`Enable ${displayName} CLI`}
            testId={`configure-agents-terminal-${cli}`}
            rowTestId={rowTestId}
            statusId={statusId}
            onToggle={
              canLaunchTerminal
                ? (next) =>
                    toggleConnectable(
                      terminalEnabledKey(cli),
                      agentIdForTerminalCli(cli),
                      'terminal',
                      next,
                      installedClis[cli] ?? null,
                    )
                : undefined
            }
          />
        );
      })}
      <FoldToggleButton
        hiddenCount={terminalHiddenCount}
        expanded={showTerminalOverflow}
        onToggle={() => setShowTerminalOverflow((v) => !v)}
        testId="configure-agents-terminal-show-more"
      />
    </AgentGroup>
  ) : null;

  const desktopGroup = showDesktop ? (
    <AgentGroup
      key="desktop"
      label={t`External apps`}
      labelId="settings-configure-agents-desktop"
      labelIcon={<ArrowUpRight aria-hidden="true" className="size-3" />}
    >
      {desktopShown.map((target) => {
        const installed = states[target.id]?.installed ?? null;
        const { displayName } = target;
        const enabled = isDesktopTargetEnabled(overrides, target.id, installed);
        const presence = rowPresence(agentIdForHandoffTarget(target.id), installed);
        const rowTestId = `configure-agents-desktop-row-${target.id}`;
        const { status, action, hintAction, residualFiles, statusId } = connectionSlots(
          agentIdForHandoffTarget(target.id),
          t`${displayName} Desktop`,
          rowTestId,
          'external',
          enabled,
          installed,
          presence,
        );
        return (
          <AgentRow
            key={target.id}
            icon={<TargetIcon id={target.id} className="size-4" aria-hidden="true" />}
            name={t`${displayName} Desktop`}
            hint={
              presence === 'absent'
                ? { text: presenceHint('not-installed', residualFiles), action: hintAction }
                : undefined
            }
            status={status}
            action={
              <>
                {action}
                {workspace === null ? null : (
                  <ResetHandoffSetupPrompt
                    key={`${workspace.contentDir}:${target.id}`}
                    target={target.id}
                    projectDir={workspace.contentDir}
                    displayName={displayName}
                  />
                )}
              </>
            }
            checked={enabled}
            disabled={isToggleLocked(presence, enabled)}
            ariaLabel={t`Enable ${displayName} Desktop`}
            testId={`configure-agents-desktop-${target.id}`}
            rowTestId={rowTestId}
            statusId={statusId}
            onToggle={(next) =>
              toggleConnectable(
                desktopEnabledKey(target.id),
                agentIdForHandoffTarget(target.id),
                'external',
                next,
                installed,
              )
            }
          />
        );
      })}
      {unlaunchableShown.map((agentId) => {
        const connection = connections.find((c) => c.id === agentId) ?? null;
        const detected = connection?.row.detected ?? null;
        const label = connectionLabel(agentId);
        const presence = rowPresence(agentId, detected);
        const rowTestId = `agent-connection-${agentId}`;
        const slots = connectionSlots(
          agentId,
          label,
          rowTestId,
          'external',
          connection === null || !allAvailableCellsChecked(connection),
          detected,
          presence,
        );
        return (
          <AgentRow
            key={agentId}
            icon={
              <ConnectionAgentIcon agentId={agentId} className="size-4 text-muted-foreground" />
            }
            name={label}
            hint={
              presence === 'absent'
                ? {
                    text: presenceHint('not-detected', slots.residualFiles),
                    action: slots.hintAction,
                  }
                : undefined
            }
            status={slots.status}
            action={slots.action}
            ariaLabel={label}
            testId={`configure-agents-unlaunchable-${agentId}`}
            rowTestId={rowTestId}
            statusId={slots.statusId}
          />
        );
      })}
      <FoldToggleButton
        hiddenCount={desktopHiddenCount}
        expanded={showDesktopOverflow}
        onToggle={() => setShowDesktopOverflow((v) => !v)}
        testId="configure-agents-desktop-show-more"
      />
    </AgentGroup>
  ) : null;

  const groups = [
    { node: inAppGroup, hasPresent: inAppHasDetected },
    { node: terminalGroup, hasPresent: terminalHasPresent },
    { node: desktopGroup, hasPresent: desktopHasPresent },
  ]
    .sort((a, b) => Number(b.hasPresent) - Number(a.hasPresent))
    .map((g) => g.node);

  const titleId = 'settings-configure-agents-title';

  return (
    <section
      aria-labelledby={titleId}
      className="space-y-6"
      data-field="section:agent-connections"
      data-testid="settings-configure-agents"
    >
      <SettingsSectionHeader titleId={titleId} title={t(AGENT_CONNECTIONS_SECTION_LABEL)}>
        {t`Choose which agents appear in agent menus across the app, and set them up to read and update your documents.`}
      </SettingsSectionHeader>

      <div className="relative">
        <Search
          className="-translate-y-1/2 absolute top-1/2 start-2.5 size-4 text-muted-foreground"
          aria-hidden="true"
        />
        <Input
          value={query}
          onChange={(event) => updateQuery(event.target.value)}
          placeholder={t`Search agents`}
          aria-label={t`Search agents`}
          className="ps-8"
          data-testid="configure-agents-search"
        />
      </div>

      {readOnly ? (
        <div
          role="status"
          className="flex items-center gap-2 rounded-md border px-3 py-2.5 text-muted-foreground text-sm"
          data-testid="configure-agents-read-only"
        >
          <TriangleAlert aria-hidden className="size-4 shrink-0" />
          <span>
            {devBuild
              ? t`This development build can't connect agents, so it won't change the agent setup of your installed OpenKnowledge app.`
              : t`Managing agent connections is unavailable in this build.`}
          </span>
        </div>
      ) : null}

      {readFailed ? (
        <div className="flex items-center justify-between gap-3 rounded-md border px-3 py-2.5 text-muted-foreground text-sm">
          <span className="flex min-w-0 items-center gap-2">
            <WifiOff aria-hidden className="size-4 shrink-0" />
            <span role="status">{t`Couldn't check which tools are connected.`}</span>
          </span>
          <Button
            type="button"
            variant="outline"
            size="sm"
            className="shrink-0"
            onClick={() => setReloadInstallState((value) => value + 1)}
          >
            {t`Try again`}
          </Button>
        </div>
      ) : null}

      {noMatches ? (
        <p
          className="py-6 text-center text-muted-foreground text-sm"
          data-testid="configure-agents-no-results"
        >
          {t`No agents match your search.`}
        </p>
      ) : null}

      {groups}

      <ConfigureConnectionDialog
        key={`configure:${configureId ?? 'closed'}`}
        connection={configureConnection}
        paired={configureId !== null && hasPairedConnectionRows(configureId)}
        open={configureConnection !== null}
        onOpenChange={(open) => {
          if (open) return;
          if (switchRevertKey.current !== null) {
            setAgentEnabled(switchRevertKey.current, false);
            switchRevertKey.current = null;
          }
          setConfigureId(null);
        }}
        onSave={(parts, alsoRemove) =>
          configureConnection === null
            ? Promise.resolve({
                ok: false,
                report: { actions: [], conflicts: [], withheld: [] },
                snapshot: null,
              })
            : applyAndRefresh(intentsForParts(configureConnection, parts, alsoRemove)).then(
                (result) => {
                  if (result.ok) switchRevertKey.current = null;
                  return result;
                },
              )
        }
      />
      <RemoveConnectionDialog
        key={`remove:${removeId ?? 'closed'}`}
        connection={removeConnection}
        paired={removeId !== null && hasPairedConnectionRows(removeId)}
        open={removeConnection !== null}
        onOpenChange={(open) => {
          if (!open) setRemoveId(null);
        }}
        onRemove={(alsoRemove = []) =>
          removeConnection === null
            ? Promise.resolve({
                ok: false,
                report: { actions: [], conflicts: [], withheld: [] },
                snapshot: null,
              })
            : applyAndRefresh(removalIntents(removeConnection, alsoRemove))
        }
      />
    </section>
  );
}