Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

9.8 KB
Raw Blame
import React, { useEffect, useState } from 'react';
import { Link } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { ChevronRight, Settings2 } from 'lucide-react';

import { Badge } from '../ui/badge';
import { Button } from '../ui/button';
import { SettingsResourceRow, ToggleSwitch } from './SettingsPrimitives';
import { BackendLifecycleChip } from './BackendLifecycleChip';
import { SettingsPageShell } from './SettingsPageShell';
import { hubSupplyBlocks, type HubSupplyBlock } from './models/featureFlags';
import { modelsApi } from './models/modelsApi';
import { agentsWithoutModel } from './models/supply';
import { useApi, type CliStatus, type BackendRuntimeInfo } from '@/context/ApiContext';
import { useToast } from '@/context/ToastContext';
import { AGENT_BACKENDS, DEFAULT_AGENT_STATE, getBackendUiMeta } from '@/lib/agentBackends';
import { configChanges } from '@/lib/configMutations';
import { errorMessage } from '@/lib/errorMessage';

// Mirrors design.pen qVHh4 (VR/CM/Backends): one horizontal card per backend,
// in shared display order: built-in first, then native setup order. Each card
// surfaces icon + name/description + status chip + enable toggle (a
// "Built-in" badge instead for the always-enabled backend) + a
// "Configure" link that drills into the level-2 provider page. CLI path,
// detect, install, and permission profile live on the provider page now —
// keep the level-1 page about backend availability, not Agent defaults.

type AgentState = {
  enabled: boolean;
  cli_path?: string;
  status: CliStatus;
  detectedRuntime?: BackendRuntimeInfo;
};

const DEFAULT_AGENTS = DEFAULT_AGENT_STATE as Record<string, AgentState>;

const normalizeAgents = (source: any): Record<string, AgentState> => {
  const raw = source?.agents || {};
  return Object.fromEntries(
    Object.entries(DEFAULT_AGENTS).map(([name, fallback]) => {
      const next = raw?.[name] || {};
      return [
        name,
        {
          enabled: typeof next.enabled === 'boolean' ? next.enabled : fallback.enabled,
          cli_path: next.cli_path || fallback.cli_path,
          status: (next.status as CliStatus) || fallback.status,
        },
      ];
    })
  );
};

export const SettingsBackendsPage: React.FC = () => {
  const { t } = useTranslation();
  const api = useApi();
  const { showToast } = useToast();

  const [loaded, setLoaded] = useState(false);
  const [agents, setAgents] = useState<Record<string, AgentState>>(DEFAULT_AGENTS);
  const [supplyBlocks, setSupplyBlocks] = useState<ReadonlyMap<string, HubSupplyBlock>>(() => new Map());
  // Backends with an enabled Agent whose next turn fails for want of a model (the Models page's reading).
  const [withoutModel, setWithoutModel] = useState<ReadonlySet<string>>(() => new Set());

  const refreshModelAttention = React.useCallback(async () => {
    try {
      setWithoutModel(new Set(agentsWithoutModel(await modelsApi.listAgents()).map((named) => named.backend)));
    } catch {
      // Without the Model Hub projection there is nothing to flag.
    }
  }, []);

  useEffect(() => {
    void refreshModelAttention();
  }, [refreshModelAttention]);

  useEffect(() => {
    let cancelled = false;
    api
      .getConfig()
      .then((config) => {
        if (cancelled) return;
        setAgents(normalizeAgents(config));
        setSupplyBlocks(hubSupplyBlocks(config));
        setLoaded(true);
      })
      .catch(() => {
        if (!cancelled) setLoaded(true);
      });
    return () => {
      cancelled = true;
    };
  }, [api]);

  // Detect each CLI on mount so the status pill reflects reality without
  // making the user click Detect manually. Runs after the first config load.
  useEffect(() => {
    if (!loaded) return;
    let cancelled = false;
    (async () => {
      const results = await Promise.all(
        Object.entries(agents).filter(([name]) => getBackendUiMeta(name).capabilities.supports_cli).map(async ([name, agent]) => {
          try {
            const result = await api.detectCli(agent.cli_path || name, name);
            return [name, result] as const;
          } catch {
            return [name, null] as const;
          }
        })
      );
      if (cancelled) return;
      setAgents((prev) => {
        const next = { ...prev };
        for (const [name, result] of results) {
          if (!result) continue;
          next[name] = {
            ...next[name],
            cli_path: result.path || next[name].cli_path,
            status: result.status,
            detectedRuntime: result.runtime,
          };
        }
        return next;
      });
    })();
    return () => {
      cancelled = true;
    };
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loaded]);

  // Patch-write shape: send only the edited backend's field. A whole
  // ``agents`` section round-tripped from mount-time state would
  // overwrite concurrent cross-process writes (e.g. an installer
  // updating another backend's cli_path) inside the locked merge.
  const persistBackendField = async (name: string, patch: Partial<AgentState>) => {
    try {
      await api.mutateConfig(configChanges({}, patch, ['agents', name]));
      showToast(t('common.saved'), 'success');
    } catch (e) {
      showToast(errorMessage(e) || t('common.saveFailed'), 'error');
    }
  };

  const handleToggle = async (name: string, enabled: boolean) => {
    setAgents((prev) => ({ ...prev, [name]: { ...prev[name], enabled } }));
    await persistBackendField(name, { enabled });
    // Enabling a backend can create its built-in Agent, with no model selected yet.
    await refreshModelAttention();
  };

  const refreshDetectionFor = async (name: string, cli_path?: string) => {
    try {
      const result = await api.detectCli(cli_path || name, name);
      setAgents((prev) => ({
        ...prev,
        [name]: {
          ...prev[name],
          cli_path: result.path || prev[name].cli_path,
          status: result.status,
            detectedRuntime: result.runtime,
        },
      }));
    } catch {
      // ignore — chip falls back to muted "loading" pill
    }
  };

  return (
    <SettingsPageShell
      activeTab="backends"
      title={t('settings.backendsTitle')}
      subtitle={t('settings.backendsSubtitle')}
    >
      {!loaded ? (
        <div className="text-sm text-muted">{t('common.loading')}</div>
      ) : (
        <div className="flex flex-col gap-3.5">
          {AGENT_BACKENDS.map((meta) => {
            const agent = agents[meta.id];
            const Icon = meta.Icon;
            const route = meta.settingsRoute;

            return (
              <SettingsResourceRow
                key={meta.id}
                icon={Icon}
                tileClassName={meta.tileCls}
                iconClassName={meta.iconCls}
                title={meta.label}
                badges={meta.builtin && <Badge variant="secondary">{t('settings.backends.builtinBadge')}</Badge>}
                detail={t(meta.descriptionKey)}
                actions={
                  <>
                    {supplyBlocks.has(meta.id) ? (
                      <Badge variant="warning">
                        {supplyBlocks.get(meta.id) === 'hub_disabled'
                          ? t('settings.backends.hubDisabled')
                          : supplyBlocks.get(meta.id) === 'no_source'
                            ? t('settings.backends.noModelSource')
                            : t('settings.models.shell.stopped')}
                      </Badge>
                    ) : agent.enabled && withoutModel.has(meta.id) && (
                      <Badge variant="warning">{t('settings.models.gateway.agentIssues.modelMissing')}</Badge>
                    )}
                    {meta.capabilities.supports_runtime_refresh && <BackendLifecycleChip
                      name={meta.id}
                      enabled={agent.enabled}
                      cliStatus={agent.status}
                      cliPath={agent.cli_path || ''}
                      detectedRuntime={agent.detectedRuntime}
                      onChanged={async (info) => {
                        const observed = info?.observation;
                        if (observed) {
                          setAgents((prev) => observed.cli_path === (prev[meta.id].cli_path || meta.id)
                            ? { ...prev, [meta.id]: { ...prev[meta.id], cli_path: observed.resolved_path || prev[meta.id].cli_path,
                              status: observed.status || 'unknown', detectedRuntime: observed } } : prev);
                          return;
                        }
                        const installedPath = info?.installedPath || null;
                        if (installedPath) {
                          setAgents((prev) => ({
                            ...prev,
                            [meta.id]: { ...prev[meta.id], cli_path: installedPath },
                          }));
                        }
                        await refreshDetectionFor(meta.id, installedPath || agent.cli_path);
                      }}
                    />}
                    {!meta.builtin && (
                      <ToggleSwitch
                        enabled={agent.enabled}
                        onClick={() => void handleToggle(meta.id, !agent.enabled)}
                      />
                    )}
                    {route && (
                      <Button asChild variant="secondary" size="xs">
                        <Link to={route} aria-label={t('settings.backends.configure', { name: meta.label }) as string}>
                          <Settings2 className="size-3.5" />
                          {t('settings.backends.configure')}
                          <ChevronRight className="size-3.5" />
                        </Link>
                      </Button>
                    )}
                  </>
                }
              />
            );
          })}
        </div>
      )}
    </SettingsPageShell>
  );
};